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

5

我的问题是:我有一个数据框列表,并为每个数据框创建距离矩阵。然后,我想提取每行的最小距离和相应的列名。我知道如何做第一步,但不知道如何做第二步。我希望这是一个简单的修复,但我无法理解它。以下是我的尝试:

#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个回答

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

谢谢,这很棒!但是这只适用于我的column.names在data.frame中的情况。如果它们在一个data.frame列表中怎么办?例如:`#创建列表中的名称:column.names.list <- list(df$column.names, df$column.names)for (i in 1:length(list.matrix)){ colnames(list.matrix[[i]]) <- column.names.list[[i]] } lapply(list.matrix, colnames)` - P. Bear
@P.Bear 我已经编辑了代码,所以它获取当前矩阵的 colnames,而不是使用外部的 column.names 变量。 - IceCreamToucan
谢谢!太棒了。这在我的真实数据上运行得很好! - P. Bear

2

或者:

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

0

可以使用colnames(data_frame)来获取列名。

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接