Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unnest one column list to many columns in tidyr

Tags:

r

tidyr

For example, I have a tidy data frame like this:

df <- tibble(id=1:2,
         ctn=list(list(a="x",b=1),
                  list(a="y",b=2)))
# A tibble: 2 x 2
     id        ctn
  <int>     <list>
1     1 <list [2]>
2     2 <list [2]>

How could I unnest ctn column to the right so that the data frame will be like this:

# A tibble: 2 x 3
     id     a     b
  <int> <chr> <dbl>
1     1     x     1
2     2     y     2
like image 487
rasyidstat Avatar asked Jul 26 '17 13:07

rasyidstat


People also ask

How do I Unnest a column in R?

The tidyr package in R is used to “tidy” up the data. The unnest() method in the package can be used to convert the data frame into an unnested object by specifying the input data and its corresponding columns to use in unnesting. The output is produced in the form of a tibble in R.

How do I convert a list to a DataFrame in R?

data. frame() can be used to convert a list to R DataFrame or create a data frame from a list. If you want the elements in the list column-wise, then use cbind otherwise you can use rbind.

What is a list column in R?

List-columns are implicit in the definition of the data frame: a data frame is a named list of equal length vectors. A list is a vector, so it's always been legitimate to use a list as a column of a data frame. However, base R doesn't make it easy to create list-columns, and data.


1 Answers

With dplyr and purrr

df %>% 
  mutate(ctn = map(ctn, as_tibble)) %>%
  unnest()
# A tibble: 2 x 3
     id     a     b
  <int> <chr> <dbl>
1     1     x     1
2     2     y     2
like image 159
Andrey Kolyadin Avatar answered Sep 30 '22 12:09

Andrey Kolyadin