如何在数据框列表中提取列名?

时间:2018-05-08 14:35:15

标签: r list dataframe

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

#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

谢谢。

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

或者:

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

答案 2 :(得分:0)

可以通过colnames(data_frame)获得列名。

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

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