2

I have a data.frame where one column contains data.frames.

data <- data.frame(ID = c(1,2))
data$DF <- list(data.frame(x = c(1,2), y = c(3,5)), data.frame(x = c(1,2,3), y = c(3,5,7)))
data
ID      DF
1       1, 2, 3, 5
2       1, 2, 3, 3, 5, 7

I would like to split this data into a long format.

ID      DF.x     DF.y
1       1        3
1       2        5
2       1        3  
2       2        5
2       3        7

Is there an easy way to do this?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Esben Eickhardt
  • 3,183
  • 2
  • 35
  • 56

1 Answers1

2

We can use unnest from tidyr

library(tidyr)
unnest(data)

Or a base R option would be

cbind(ID = rep(data$ID, sapply(data$DF, nrow)), do.call(rbind, data$DF))
akrun
  • 874,273
  • 37
  • 540
  • 662