Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set row names to multiple matrices in R

Tags:

r

matrix

purrr

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)

like image 616
Jzlia10 Avatar asked Jan 19 '26 04:01

Jzlia10


2 Answers

you could also just do this.


# 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)

my_list %>% 
  purrr::map(~as.matrix(data.frame(.x, row.names = .x$new_id) %>% select(-new_id)))  

[[1]]
  met1 met2
y   20   20
z   25   25

[[2]]
  met1 met2
b    5   22
c   15   24

like image 103
hammoire Avatar answered Jan 21 '26 17:01

hammoire


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
like image 20
tmfmnk Avatar answered Jan 21 '26 17:01

tmfmnk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!