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
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 unnest
ed 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With