【问题标题】:How do I extract column names in list of data frames?如何在数据框列表中提取列名?
【发布时间】:2018-05-08 14:35:14
【问题描述】:

我的问题是:我有一个 data.frames 列表,并为每个 data.frames 创建一个距离矩阵。然后,我想提取每行的最小距离和相应的列名。我知道如何做第一个但不知道后者。我(希望)这是一个简单的解决方法,但我无法绕过它。这是我的尝试:

#create list of matrices
A = matrix(c(5, 4, 2, 1, 5, 7), nrow=3, ncol=3, byrow = TRUE)        
B = matrix(c(2, 5, 10, 9, 8, 7), nrow=3, ncol=3, byrow = TRUE)
list.matrix <- list(A,B)

#create names
column.names <- c("A", "B", "C")
df = data.frame(column.names)

#name rows
list.matrix<-lapply(list.matrix, function(x){colnames(x)<- as.character(df$column.names); x})

#Then I can get the smallest value by row
min.list.value <- lapply(list.matrix, function(x) apply(x, 1, min)) #smallest value per row
min.list.row <-  lapply(list.matrix, function(x) (max.col(-x))) #column index of smallest value

#But how do I get the colname of the row with the smallest value??
#Something like this, which does not work (obviously)
min.list.colname <- lapply(list.matrix, function(x) apply(x, 1, colnames(min))) #smallest value per row

谢谢。

【问题讨论】:

    标签: r list dataframe


    【解决方案1】:
    min.list.colname <- lapply(min.list.row, function(x) column.names[x])
    

    您可以使用它来获取值、列索引和列名

    library(purrr)
    library(magrittr)
    
    
    list.matrix %>% 
      lapply(apply, 1, which.min) %>% 
      imap(~data.frame(value = list.matrix[[.y]][cbind(seq_along(.x), .x)]
                      , ColName = colnames(list.matrix[[.y]])[.x]
                      , ColIndex = .x))
    
    # [[1]]
    #   value ColName ColIndex
    # 1     2       C        3
    # 2     1       A        1
    # 3     2       C        3
    # 
    # [[2]]
    #   value ColName ColIndex
    # 1     2       A        1
    # 2     7       C        3
    # 3     2       A        1
    

    【讨论】:

    • 谢谢,太好了!但这仅适用于我的 column.names 在 data.frame 中的情况。如果它们在 data.frames 列表中怎么办?例如#create names in list: column.names.list &lt;- list(df$column.names, df$column.names) for (i in 1:length(list.matrix)){ colnames(list.matrix[[i]]) &lt;- column.names.list[[i]] } lapply(list.matrix, colnames)
    • @P.Bear 我已经编辑了代码,所以它可以获取当前矩阵的colnames,而不是使用外部的column.names 变量。
    • 谢谢!杰出的。这就像我的真实数据的魅力!
    【解决方案2】:

    或者:

    (min.list.colname <- lapply(list.matrix, function(x) colnames(x)[apply(x, 1, which.min)]))
    

    【讨论】:

      【解决方案3】:

      列名可以获取为colnames(data_frame)

      现在使用 transpose 将列名作为列表获取:

      colnames_df <- t(t(colnames(data_frame))
      

      【讨论】:

        猜你喜欢
        • 2015-11-21
        • 1970-01-01
        • 2019-10-31
        • 1970-01-01
        • 2021-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多