1

I have a question about de-summarize a dataframe in R. I have the following dataframe:

  A  B
  ----
  X  c(1,2,4)
  C  c(1,4,3)
  V  c(5,3,2)
  B  c(2,4,5,6)

So, in the B column are vectors. I want to turn this dataframe into the following:

  B  A
  ----
  1  X
  1  C
  2  X
  2  V
  2  B
  3  C
  3  V
  4  X
  4  C
  4  B
  5  B
  6  B

Maybe someone has an idea how I can convert this table?

Kind regards

nuwuwa
  • 103
  • 9

1 Answers1

1

We can use unnest from tidyr to unnest the list column and then arrange by column 'B'

library(tidyr)
library(dplyr)
unnest(df1, B) %>%
    arrange(B) %>%
    select(B, A)
# A tibble: 13 x 2
#       B A    
#   <dbl> <chr>
# 1     1 X    
# 2     1 C    
# 3     2 X    
# 4     2 V    
# 5     2 B    
# 6     3 C    
# 7     3 V    
# 8     4 X    
# 9     4 C    
#10     4 B    
#11     5 V    
#12     5 B    
#13     6 B    

Or create a named list i.e. name the list column 'B' with 'A' elements and stack it to a two column data.frame in base R

with(df1, stack(setNames(B, A)))

data

df1 <- structure(list(A = c("X", "C", "V", "B"), B = list(c(1, 2, 4), 
    c(1, 4, 3), c(5, 3, 2), c(2, 4, 5, 6))), row.names = c(NA, 
-4L), class = "data.frame")
akrun
  • 874,273
  • 37
  • 540
  • 662