将行名称设置为R中的多个矩阵

wdebmtf2  于 2023-03-27  发布在  其他
关注(0)|答案(3)|浏览(111)

我有一个由两个 Dataframe 组成的列表。在此基础上,我创建了一个带有数值变量的矩阵。在下一步中,我试图根据原始列表的列将行名称设置为矩阵。然而,这不起作用。将行名称设置为原始列表确实有效。有人知道问题在哪里吗?

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

创建于2020-04-14由reprex package(v0.3.0)

oalqel3c

oalqel3c1#

你也可以这样做。

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

y4ekin9u2#

一种选择可以是:

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
r6vfmomb

r6vfmomb3#

一个更好的选择是使用rownames.force参数到as.matrix作为data.frame输入:

my_list %>% 
    purrr::map(~dplyr::select(.x, met1, met2)) %>% map(as.matrix,rownames.force=TRUE)

相关问题