Home > Back-end >  Converting a matrix into a tibble in R
Converting a matrix into a tibble in R

Time:11-13

How can I convert this matrix:

> matrix(1:3, nrow = 3, dimnames = list(c("X","Y","Z"), c("A")))
  A
X 1
Y 2
Z 3

into this tibble:

> tibble::tribble(~group1, ~group2, ~value, "X", "A", 1, "Y", "A", 2, "Z", "A", 3)
# A tibble: 3 × 3
  group1 group2 value
  <chr>  <chr>  <dbl>
1 X      A          1
2 Y      A          2
3 Z      A          3

Thank you

CodePudding user response:

as.tibble can convert the matrix's rownames to a column, and then you can use gather() to create the group2 column:

library(tidyverse)

m <- matrix(1:3, nrow = 3, dimnames = list(c("X","Y","Z"), c("A")))

newtib <- m %>%
    as.tibble(rownames = "group1") %>%
    gather('A', key = "group2", value = "value")

> newtib
# A tibble: 3 × 3
  group1 group2 value
  <chr>  <chr>  <int>
1 X      A          1
2 Y      A          2
3 Z      A          3

> tibble::tribble(~group1, ~group2, ~value, "X", "A", 1, "Y", "A", 2, "Z", "A", 3)
# A tibble: 3 × 3
  group1 group2 value
  <chr>  <chr>  <dbl>
1 X      A          1
2 Y      A          2
3 Z      A          3

CodePudding user response:

  1. Transform your matrix into a dataframe
  2. bring your rownames to column group1
  3. mutate group2
data.frame(matrix) %>% 
  rownames_to_column("group1") %>% 
  mutate(group2 = colnames(matrix)) %>% 
  dplyr::select(group1, group2, value=A)
  group1 group2 value
1      X      A     1
2      Y      A     2
3      Z      A     3

CodePudding user response:

Easier with base R, if we convert to table and coerce with as.data.frame (if we need to convert to tibble - use as_tibble as wrapper over the as.data.frame

as.data.frame(as.table(m1))
  Var1 Var2 Freq
1    X    A    1
2    Y    A    2
3    Z    A    3

data

m1 <- matrix(1:3, nrow = 3, dimnames = list(c("X","Y","Z"), c("A")))

CodePudding user response:

You can use -

library(tidyverse)

mat <- matrix(1:3, nrow = 3, dimnames = list(c("X","Y","Z"), c("A")))

mat  %>%
  as.data.frame() %>%
  rownames_to_column(var = 'group1') %>%
  pivot_longer(cols = -group1, names_to = 'group2')

#  group1 group2 value
#  <chr>  <chr>  <dbl>
#1 X      A          1
#2 Y      A          2
#3 Z      A          3
  • Related