My problem is this: I have a list of data.frames and create a distance matrix for each data.frame. Then, I want to extract the minimum distance for each row and the corresponding column name. I know how to do the first but not the latter. I (hope) this is an easy fix but I can't wrap my head around it. Here is my attempt:
#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
Thank you.
min.list.colname <- lapply(min.list.row, function(x) column.names[x])
You can use this to get values, column indices, and column names
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With