Home > Blockchain >  List in R data frame
List in R data frame

Time:11-15

This is an example of my data frame with a list in it.

df <- data.frame(x = 1:2, y = c("A", "B"))
df$z <- rep(list(1:3), 2)
df

> df
  x y       z
1 1 A 1, 2, 3
2 2 B 1, 2, 3

I would like to kind of unlist the list and rearrange the data frame as following:

  x y z
1 1 A 1
2 1 A 2
3 1 A 3
4 2 B 1
5 2 B 2
6 2 B 3

Tried unlist(df) but could not get it right.

CodePudding user response:

tidyr::unnest(df,z) # or even unnest_longer(df, z)

# A tibble: 6 × 3
      x y         z
  <int> <chr> <int>
1     1 A         1
2     1 A         2
3     1 A         3
4     2 B         1
5     2 B         2
6     2 B         3

CodePudding user response:

Maybe try something like this:

require(dplyr)
df %>% 
  apply(1, function(x) expand.grid(x[1][[1]], x[2][[1]], x[3][[1]])) %>% 
  reduce(rbind)
  • Related