这是我目前的问题。我有一个包含不同值的数据帧列表。我希望能够遍历数据框列表,并根据我指定的列名称为每个数据框选择特定的数据列。然后,我想在单独的数据帧列表中分配这些选定的列。
我使用了另一个列表对象,该对象由要提取的不同列的名称组成。
我已经采取了几种方法,但是我仍然处于从头开始的阶段。帮助将不胜感激!
这是我在下面编写的一些示例代码:
# Create sample data set of five data frames, 10 x 10
M1 <- data.frame(matrix(rnorm(5), nrow = 10, ncol = 10))
M2 <- data.frame(matrix(rnorm(10), nrow = 10, ncol = 10))
M3 <- data.frame(matrix(rnorm(15), nrow = 10, ncol = 10))
M4 <- data.frame(matrix(rnorm(20), nrow = 10, ncol = 10))
M5 <- data.frame(matrix(rnorm(25), nrow = 10, ncol = 10))
# Assign data frames to a list object
mlist<-list(M1, M2, M3, M4, M5)
# Creates a data frame object consisting of the different column names I want to extract later
df.names <- data.frame(One = c("X1", "X3", "X5"), Two = c("X2", "X4", "X6"))
# Converts df.names into a set of characters (not sure if this is needed but it has worked for me in the past)
df.char <- lapply(df.names, function(x) as.character(x[1:length(x)]))
# Creates variable m that will be used to iterate in the for loops below
m<-1:length(mlist)
# Creates list object to set aside selected columns from df.names
mlist.selected<-list()
# A for loop to iterate for each of the df.names elements, and for each dataframe in mlist. *Hopefully* select out the columns of interest labeled in df.names, place into another list object for safe keeping
for (i in 1:length(df.names))
{
for(j in m)
{
#T his is the line of code I'm struggling with and I know it doesn't work. :-(
mlist.selected[j]<-lapply(mlist, function(x) x[df.char[[i]]])
}
}
使用
mlist.selected[[j]] <- lapply(mlist, function(x) x[df.char[[i]]])
在您的for循环中将使您更加接近。我建议使用命名列表
mlist.selected[[paste("m",j, names(df.names)[i], sep=".")]] <-
lapply(mlist, function(x) x[df.char[[i]]])
以获得更好的输出。
在检查时,这将返回重复的列表,我认为您不需要。如果我了解您要执行的操作,则实际上可以摆脱内部(j)循环:
# create named list of the data.frames
mlist<-list("M1"=M1, "M2"=M2, "M3"=M3, "M4"=M4, "M5"=M5)
# run the loop
for (i in 1:length(df.names)) {
mlist.selected[[paste(names(df.names)[i], sep=".")]] <-
lapply(mlist, function(x) x[df.char[[i]]])
}
这将返回一个名称正确的列表以供使用。例如,你可以从M2访问保存矢量数据df.names$Two
使用mlist.selected$Two$M2
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句