我的问题是:我有一个数据框列表,并为每个数据框创建距离矩阵。然后,我想提取每行的最小距离和相应的列名。我知道如何做第一步,但不知道如何做第二步。我希望这是一个简单的修复,但我无法理解它。以下是我的尝试:
#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
谢谢您。
colnames
,而不是使用外部的column.names
变量。 - IceCreamToucan