Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract column names in list of data frames?

Tags:

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.

like image 731
P. Bear Avatar asked May 08 '18 14:05

P. Bear


1 Answers

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
like image 200
IceCreamToucan Avatar answered Sep 28 '22 19:09

IceCreamToucan