总之,我有一个用于导入存储在几个txt文件中的大量数据的脚本。在一个独立文件而不是中,所有的行都要放在同一个表中(DF现在切换到DT),因此对于每个文件,我选择属于它的所有DF、get DF和assign的行。
当我第一次创建一个名为table1的DF时,我会这样做:
name <- "table1" # in my code the value of name will depend on different factors
# and **not** known in advance
assign(name, someRows)然后,在执行过程中,我的代码可能会(在其他文件中)在table1数据框架中找到其他行,因此:
name <- "table"
assign(name, rbindfill(get(name), someRows))我的问题是:assign(get(string), anyObject)是以编程方式完成作业的最佳方式吗?谢谢
编辑:
下面是我的代码的简化版本:( dataSource中的每一项都是read.table()的结果,所以只有一个文本文件)
set.seed(1)
#
dataSource <- list(data.frame(fileType = rep(letters[1:2], each=4),
id = rep(LETTERS[1:4], each=2),
var1 = as.integer(rnorm(8))),
data.frame(fileType = rep(letters[1:2], each=4),
id = rep(LETTERS[1:4], each=2),
var1 = as.integer(rnorm(8))))
# # #
#
library(plyr)
#
tablesnames <- unique(unlist(lapply(dataSource,function(x) as.character(unique(x[,1])))))
for(l in tablesnames){
temp <- lapply(dataSource, function(x) x[x[,1]==l, -1])
if(exists(l)) assign(l, rbind.fill(get(l), rbind.fill(temp))) else assign(l, rbind.fill(temp))
}
#
#
# now two data frames a and b are crated
#
#
# different method using rbindlist in place of rbind.fill (faster and, until now, I don't # have missing column to fill)
#
rm(a,b)
library(data.table)
#
tablesnames <- unique(unlist(lapply(dataSource,function(x) as.character(unique(x[,1])))))
for(l in tablesnames){
temp <- lapply(dataSource, function(x) x[x[,1]==l, -1])
if(exists(l)) assign(l, rbindlist(list(get(l), rbindlist(temp)))) else assign(l, rbindlist(temp))
}发布于 2013-05-14 12:26:48
我建议使用命名的list,并跳过使用assign和get。许多很酷的R特性(例如lapply)在列表上工作得很好,并且不适合使用assign和get。此外,您可以很容易地将列表传递给一个函数,而对于与assign和get组合在一起的一组变量来说,这可能有点麻烦。
如果您想要将一组文件读入一个大的data.frame中,我将使用类似这样的方法(假设csv类似文本文件):
library(plyr)
list_of_files = list.files(pattern = "*.csv")
big_dataframe = ldply(list_of_files, read.csv)或者,如果您希望将结果保存在列表中:
big_list = lapply(list_of_files, read.csv)并可能使用rbind.fill
big_dataframe = do.call("rbind.fill", big_list)https://stackoverflow.com/questions/16542781
复制相似问题