Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

My data frame contains the output of a survey with a select multiple question type. Some cells have multiple values.

df <- data.frame(a=1:3,b=I(list(1,1:2,1:3)))

df

  a       b

1 1       1

2 2    1, 2

3 3 1, 2, 3

I would like to flatten out the list to obtain the following output:

df

  a       b

1 1       1

2 2       1

3 2       2

4 3       1

5 3       2

6 3       3

should be easy but somehow I can't find the search terms. thanks.

1 Answer

0 votes
by (108k points)

You can simply use unnest from "tidyr", refer the following code:

library(tidyr)

unnest(df, b)

#   a b

# 1 1 1

# 2 2 1

# 3 2 2

# 4 3 1

# 5 3 2

# 6 3 3 

Browse Categories

...