我需要通过同一组代码处理数百个数据帧。为了便于说明,我创建了3个数据框:
ds.1 = as.data.frame(matrix(c(1, 0.15, 0.15, 0.15,
0.2, 1, 0.15, 0.15,
0.2, .15, 1, 0.15,
0.2, 0.15, 0.15, 1), nrow=4, ncol=4))
ds.2 = as.data.frame(matrix(c(1, 0.25, 0.25, 0.25,
0.2, 1, 0.25, 0.25,
0.2, .25, 1, 0.25,
0.2, 0.25, 0.25, 1), nrow=4, ncol=4))
ds.3 = as.data.frame(matrix(c(1, 0.50, 0.50, 0.50,
0.2, 1, 0.50, 0.50,
0.2, .50, 1, 0.50,
0.2, 0.50, 0.50, 1), nrow=4, ncol=4))
然后,我将数据帧名分配给一个向量。
ds.vector <- c("ds.1", "ds.2", "ds.3") #create a vector of data set names
我计算向量中数据帧的数量
ds.in.vector <- length(ds.vector) #count the number of elements in vector
我循环遍历向量,并试图将数据帧名分配给一个名为ds的数据帧。然后我会在ds上运行代码。
for (i in 1:ds.in.vector)
{
ds <- ds.vector[i] #copy each of the data sets into ds
#There would be a bunch of code here. For this example,
# I will just try to print
print(ds)
}
行: ds <- ds.vectori不会将其名称在向量中的数据帧复制到ds中。相反,它将向量的字符串复制到ds中。
发布于 2015-12-10 16:34:05
这些data.frames属于一个列表。您应该在创建它们时将它们分配为一个。在你的全球环境中拥有成百上千的data.frames是疯狂的,也是不切实际的。
ds.list <- list(
ds.1 = as.data.frame(matrix(c(1, 0.15, 0.15, 0.15,
0.2, 1, 0.15, 0.15,
0.2, .15, 1, 0.15,
0.2, 0.15, 0.15, 1), nrow=4, ncol=4)),
ds.2 = as.data.frame(matrix(c(1, 0.25, 0.25, 0.25,
0.2, 1, 0.25, 0.25,
0.2, .25, 1, 0.25,
0.2, 0.25, 0.25, 1), nrow=4, ncol=4)),
ds.3 = as.data.frame(matrix(c(1, 0.50, 0.50, 0.50,
0.2, 1, 0.50, 0.50,
0.2, .50, 1, 0.50,
0.2, 0.50, 0.50, 1), nrow=4, ncol=4))
)
ds.vector <- c("ds.1", "ds.2", "ds.3")
for (i in seq_along(ds.vector)) {
ds <- ds.list[ds.vector[i]] #copy each of the data sets into ds
#There would be a bunch of code here. For this example,
# I will just try to print
print(ds)
}
当然,如果它们都具有相同的结构,您可以将它们组合成一个数据结构:
library(data.table)
DT <- rbindlist(ds.list, idcol=TRUE)
DT[, print(.SD), by = .id]
发布于 2015-12-10 16:39:57
一种方法(尽管效率不是很高)是:
ds.cumulated <- get(ds.vector[1])
for (i in 2:ds.in.vector)
{
ds.i <- get(ds.vector[i])
ds.cumulated <- rbind(ds.cumulated, ds.i)
}
https://stackoverflow.com/questions/34206811
复制相似问题