【发布时间】:2015-06-20 06:55:09
【问题描述】:
如何使用 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
尝试 1:
我的第一种方法是将data("faithful") 分配给x。但是data() 返回一个字符串。所以现在我的环境中有 df faithful 和字符向量 x。
> x <- data("faithful")
> x
[1] "faithful" # String, not the df "faithful" from the datasets package
> ls()
[1] "faithful" "x"
尝试 2: 在我的第二次尝试中尝试变得更复杂一些。
> x <- get(data("faithful")) # This works as far as assignment goes
> ls() # However I still get the duplicate copy
[1] "faithful" "x"
关于我尝试这样做的动机的简短说明。我有一个包含 5 个非常大的 data.frames 的 R 包 - 每个都有相同的列。我想在所有 5 个 data.frames 上有效地生成相同的计算列。所以我想在list() 构造函数中使用data() 将5 个data.frames 放入一个列表中。然后我想使用plyr 包中的llply() 和mutate() 来迭代列表中的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)
但我想创建一个命名列表 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
但我终于能够以以下方式构造延迟加载的 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))
【问题讨论】:
-
您可以在将数据分配到您的列表后立即删除它,例如
data( "faithful" ); x <- faithful; rm( faithful ) -
@vaettchen 这绝对是一个选择。只是想知道技术上是否存在跳过将额外副本加载到环境中的方法。