Convert tibble into matrix

I want to convert a tibble into a matrix with the first column of the tibble as row names of the matrix.

Currently I'm doing like this:

my_tibble = tibble(row_name = letters[1:10], a = 1:10, b = 11:20, c = 21:30)

row_name = my_tibble$row_name
my_tibble %<>% select(-row_name) %>% as.matrix
rownames(my_tibble) = row_name

Is there a pre-built tidyverse function for this job?

1 Like

you could write your own function, then use it like so

library(tidyverse)

make_matrix <- function(df,rownames = NULL){
  my_matrix <-  as.matrix(df)
  if(!is.null(rownames))
    rownames(my_matrix) = rownames
  my_matrix
}

(my_tibble = tibble(row_name = letters[1:10], a = 1:10, b = 11:20, c = 21:30))
(my_matrix <- make_matrix(select(my_tibble,-row_name),
                         pull(my_tibble,row_name)))
2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.