【发布时间】:2016-11-11 03:37:06
【问题描述】:
这是我目前的问题。我有一个包含不同值的数据框列表。我希望能够遍历数据框列表,并根据我指定的列的名称为每个数据框选择特定的数据列。然后,我想将这些选定的列分配到单独的数据框列表中。
我使用了另一个列表对象,其中包含我要提取的不同列的名称。
我尝试了几种方法,但仍处于摸索阶段。帮助将不胜感激!
这是我在下面编写的一些示例代码:
# 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]]])
}
}
【问题讨论】:
标签: r for-loop dataframe subset