Search code examples
rtidyversereshape2

Create table from acast function ouput [r]


I would like to create a table from acast function from reshape2 package. I have provided example here where I create result I need 'by hand', I need to know if there is a function to do so in R.

library(tidyverse)
library(reshape2)

mtcars %>% 
  head(6) %>% 
  add_rownames(var = "Names") %>% 
  acast(Names ~ gear)

# What I want to create is 
tibble(
  `3` = c("Hornet 4 Drive", "Hornet Sportabout", "Valiant"),
  `4` = c("Datsun 710", "Mazda RX4", "Mazda RX4 Wag"))


Solution

  • This might do the job then:

    head(mtcars) %>% 
      select(gear) %>% 
      rownames_to_column(var = "model") %>% 
      pivot_wider(names_from = gear, values_from = model) %>% 
      apply(2, unlist)