Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unnest one of several list columns in dataframe

Tags:

r

tidyr

I have a tibble with several list columns and I'd like to only unnest one of them.

Example

library(dplyr)
library(purrr)
library(tidyr)
library(stringr)

iris %>% 
  group_by(Species) %>% 
  nest() %>% 
  mutate(sum_data = map(data,
                        ~.x %>% 
                          summarize_all(mean) %>% 
                          rename_all(funs(str_c("Mean.", .))))) 

# A tibble: 3 x 3
#      Species              data         sum_data
#       <fctr>            <list>           <list>
# 1     setosa <tibble [50 x 4]> <tibble [1 x 4]>
# 2 versicolor <tibble [50 x 4]> <tibble [1 x 4]>
# 3  virginica <tibble [50 x 4]> <tibble [1 x 4]>

Now I would like to keep the nested data column, but unnest the sum_data column, without specifically specifying each columnname in sum_data and also without unnesting the whole dataset and then renesting the data column.

Desired outcome

# A tibble: 3 x 6
#      Species              data Mean.Sepal.Length Mean.Sepal.Width Mean.Petal.Length Mean.Petal.Width
#       <fctr>            <list>             <dbl>            <dbl>             <dbl>            <dbl>
# 1     setosa <tibble [50 x 4]>             5.006            3.428             1.462            0.246
# 2 versicolor <tibble [50 x 4]>             5.936            2.770             4.260            1.326
# 3  virginica <tibble [50 x 4]>             6.588            2.974             5.552            2.026
like image 434
kath Avatar asked Jan 31 '18 09:01

kath


1 Answers

According to unnest, the argument ...

Specification of columns to nest. Use bare variable names or functions of variables. If omitted, defaults to all list-cols.

Therefore, we could specify the column name to be unnested after the rename_all

iris %>
  ... #op's code
  ...

  rename_all(funs(str_c("Mean.", .))))) %>%
  unnest(sum_data)
# A tibble: 3 x 6
#  Species    data              Mean.Sepal.Length Mean.Sepal.Width Mean.Petal.Length Mean.Petal.Width
#  <fctr>     <list>                        <dbl>            <dbl>             <dbl>            <dbl>
#1 setosa     <tibble [50 x 4]>              5.01             3.43              1.46            0.246
#2 versicolor <tibble [50 x 4]>              5.94             2.77              4.26            1.33 
#3 virginica  <tibble [50 x 4]>              6.59             2.97              5.55            2.03 
like image 77
akrun Avatar answered Oct 29 '22 19:10

akrun