Search code examples
rmatrixpurrr

Set row names to multiple matrices in R


I have a list that consists of two dataframes. Based on this I created a matrix with numeric variables. In the next step, I try to set row names to the matrix based on a column of the original list. However, this does not work. Setting row names to the original list does work. Does anyone know where the problem is?

install.packages("purrr")
library(purrr)

# Data
data1 <- data.frame(new_id = c("y", "z"), met1 = c(20, 25),  met2 = c(20, 25))
data2 <- data.frame(new_id = c("b", "c"), met1 = c(5, 15), met2 =c(22, 24))

my_list <- list(data1, data2) # List of two dataframes

my_list
#> [[1]]
#>   new_id met1 met2
#> 1      y   20   20
#> 2      z   25   25
#> 
#> [[2]]
#>   new_id met1 met2
#> 1      b    5   22
#> 2      c   15   24

# Set row names: new_id
my_list1 <- my_list %>% 
    purrr::map(~data.frame(.x, row.names = .x$new_id)) # Works

my_list1
#> [[1]]
#>   new_id met1 met2
#> y      y   20   20
#> z      z   25   25
#> 
#> [[2]]
#>   new_id met1 met2
#> b      b    5   22
#> c      c   15   24

# Convert "my_list" into matrix and select numeric vars met1 and met2
matrix <- my_list %>% 
   purrr::map(~dplyr::select(.x, met1, met2)) %>% 
   purrr::map(as.matrix)
 
# Convert "num_slct" to matrix and set row.names
  matrix %>% 
  purrr::map(~.x, row.names = my_list$new_id) # set row.names does not work
#> [[1]]
#>      met1 met2
#> [1,]   20   20
#> [2,]   25   25
#> 
#> [[2]]
#>      met1 met2
#> [1,]    5   22
#> [2,]   15   24

Created on 2020-04-14 by the reprex package (v0.3.0)


Solution

  • One option could be:

    map(.x = my_list, ~ as.matrix(.x[-1]) %>%
         `rownames<-`(.x$new_id))
    
    [[1]]
      met1 met2
    y   20   20
    z   25   25
    
    [[2]]
      met1 met2
    b    5   22
    c   15   24