【问题标题】:Selecting out specific columns in data frames embedded within a list选择嵌入在列表中的数据框中的特定列
【发布时间】: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


    【解决方案1】:

    使用

    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]]])
    }
    

    返回一个命名良好的列表以供使用。例如,您可以使用mlist.selected$Two$M2 访问df.names$Two 中M2 中保存的矢量数据。

    【讨论】:

    • 我发现简化 for 循环会导致最佳输出.... for (i in 1:length(df.names)) { mlist.selected[[paste("m", i, 名称(df.names)[i], sep = ".")]]
    • 对。这是我的答案的底部。我什至添加了一些内容来从 mlist 中获取正确的 data.frame 名称。看看吧。
    • 感谢您的帮助!
    猜你喜欢
    • 2021-11-04
    • 2016-07-30
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多