返回在RData文件中存儲為變量的值的函數(沒有全局變量)

[英]function that returns a value stored as a variable in an RData file (without global vars)


I want to get a specific variable value from a stored RData file. Often times in R sample code, the data set is loaded involving global variables.

我想從存儲的RData文件中獲取特定的變量值。在R示例代碼中,通常會加載涉及全局變量的數據集。

I want to avoid any global variables and instead write a function that returns the value of a variable stored in an RData file. (This makes is also more explicit which variable is needed.)

我想避免任何全局變量,而是編寫一個函數,返回存儲在RData文件中的變量的值。 (這使得更明確需要哪個變量。)

How can I program a function returns a value stored as a variable in an RData file (without using any global variables).

如何編程函數返回存儲為RData文件中的變量的值(不使用任何全局變量)。

(My try ist the function getVariableFromRDatabelow, but it is a bit cumbersome and perhaps not correct.)

(我的嘗試是函數getVariableFromRDatabelow,但它有點麻煩,也許不正確。)

xx <- pi # to ensure there is some data
save(list = ls(all = TRUE), file= "all.RData")
rm(xx)

getVariableFromRData <- function(dataName, varName) {
    e <- new.env()
    load(dataName, envir=e)

    if(varName %in% ls(e)) {
        resultVar <- e[[varName]]
        return(resultVar)
    } else {
        stop (paste0("!! Error: varname (", varName,
                      ") not found in RData (", dataName, ")!"))
    }
}


yy <- getVariableFromRData("all.RData", "xx")

1 个解决方案

#1


1  

Your solution looks decent. Compare w/a function I wrote (based on some old SO question) to modify a .Rdata file:

您的解決方案看起比較w /我寫的函數(基於一些舊的SO問題)來修改.Rdata文件:

resave<- function (..., list = character(), file) 
{
    previous <- load(file)
    var.names <- c(list, as.character(substitute(list(...)))[-1L])
    for (var in var.names) assign(var, get(var, envir = parent.frame()))
    save(list = unique(c(previous, var.names)), file = file)
}

So strictly speaking you don't need a new environment: you can just query the output of load to see if the desired variable name is there.

嚴格來說,您不需要新的環境:您只需查詢加載的輸出,以查看是否存在所需的變量名稱。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/08/24/ff6153c9a6187c6b270f8dab84b73018.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com