如何使用该data()函数从 R 包加载数据集,并将其直接分配给变量,而无需在您的环境中创建重复副本?
简而言之,您是否可以在不在您的环境中创建两个相同的 dfs 的情况下执行此操作:
> data("faithful") # Old Faithful Geyser Data from datasets package
> x <- faithful
> ls() # Now I have 2 identical dfs - x and faithful - in my environment
[1] "faithful" "x"
> remove(faithful) # Now I've removed one of the redundant dfs
Run Code Online (Sandbox Code Playgroud)
尝试 1:
我的第一种方法是只分配data("faithful")给x. 但data()返回一个字符串。所以现在我的环境中有 dffaithful和字符向量x。
> x <- data("faithful")
> x
[1] "faithful" # String, not the df "faithful" from the datasets package
> ls()
[1] "faithful" "x"
Run Code Online (Sandbox Code Playgroud)
尝试 2: 在我的第二次尝试中尝试变得更复杂一些。
> x <- get(data("faithful")) # This works as far as assignment goes
> ls() # However I still get the duplicate copy
[1] "faithful" "x"
Run Code Online (Sandbox Code Playgroud)
关于我尝试这样做的动机的简短说明。我有一个包含 5 个非常大的 data.frames 的 R 包 - 每个都有相同的列。我想在所有 5 个 data.frames 上有效地生成相同的计算列。所以我想data()在list()构造函数中使用将 5 个 data.frames 放入一个列表中。然后我想使用llply()和mutate()从plyr包中迭代列表中的 dfs 并为每个 df 创建计算列。但是我不想在我的环境中放置 5 个大型数据集的重复副本,因为这是在具有 RAM 限制的 Shiny 应用程序中。
编辑: 我能够从他的回答中使用@henfiber 的两种方法来找出如何将整个 data.frames 延迟加载到命名列表中。
这里的第一个命令用于将 data.frame 分配给新的变量名称。
# this loads faithful into a variable x.
# Note we don't need to use the data() function to load faithful
> delayedAssign("x",faithful)
Run Code Online (Sandbox Code Playgroud)
但是,我想创建一个名为列表x的元素y = data(faithful),z=data(iris)等等。
我尝试了下面的方法,但没有用。
> x <- list(delayedAssign("y",faithful),delayedAssign("z", iris))
> ls()
[1] "x" "y" "z" # x is a list with 2 nulls, y & z are promises to faithful & iris
Run Code Online (Sandbox Code Playgroud)
但我终于能够以下列方式构造一个延迟加载的 data.frame 对象列表:
# define this function provided by henfiber
getdata <- function(...)
{
e <- new.env()
name <- data(..., envir = e)[1]
e[[name]]
}
# now create your list, this gives you one object "x" of class list
# with elements "y" and "z" which are your data.frames
x <- list(y=getdata(faithful),z=getdata(iris))
Run Code Online (Sandbox Code Playgroud)
使用辅助函数:
# define this function
getdata <- function(...)
{
e <- new.env()
name <- data(..., envir = e)[1]
e[[name]]
}
# now load your data calling getdata()
x <- getdata("faithful")
Run Code Online (Sandbox Code Playgroud)
或者使用匿名函数:
x <- (function(...)get(data(...,envir = new.env())))("faithful")
Run Code Online (Sandbox Code Playgroud)
您还应该考虑lazy loading将数据添加LazyData: true到包的描述文件中。
如果您RStudio在运行后使用data("faithful"),您将在面板上看到Environment“忠实”的 data.frame 被调用"promise"(另一个不太常见的名称是"thunk")并且呈灰色显示。这意味着它由 R 延迟计算,并且尚未加载到内存中。您甚至可以"x"使用以下delayedAssign()函数延迟加载变量:
data("faithful") # lazy load "faithful"
delayedAssign("x", faithful) # lazy assign "x" with a reference to "faithful"
rm(faithful) # remove "faithful"
Run Code Online (Sandbox Code Playgroud)
仍然没有任何内容被加载到内存中
summary(x) # now x has been loaded and evaluated
Run Code Online (Sandbox Code Playgroud)
lazy evaluation 在这里了解更多信息。