Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

List in R data frame

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading