简体   繁体   中英

R unnest multiple columns

Any functional approach to unnest multiple columns of different sizes?

Example:

library(tidyr)
library(dplyr)

my_list <- list(year = 2018:2020, period = 1, id = c(17,35))

expand_grid(my_list) %>%
  pivot_wider(
    names_from = my_list,
    values_from = my_list
  ) %>%
  rename_at(., names(.), ~ names(my_list))
# A tibble: 1 x 3
  year         period       id          
  <named list> <named list> <named list>
1 <int [3]>    <dbl [1]>    <dbl [2]>   
expand_grid(my_list) %>%
  pivot_wider(
    names_from = my_list,
    values_from = my_list
  ) %>%
  rename_at(., names(.), ~ names(my_list)) %>%
  unnest(cols = names(my_list))
Erro: Incompatible lengths: 3, 2.

unnest requires column names, is it possible for a string vector?

Expected:

# A tibble: 1 x 3
  year  period   id          
  <int> <int>  <int>
1 2018   1    17
2 2019   1    17
3 2020   1    17
4 2018   1    35
5 2019   1    35
6 2020   1    35

We can use cross_df from purrr :

purrr::cross_df(my_list)

#   year period    id
#  <int>  <dbl> <dbl>
#1  2018      1    17
#2  2019      1    17
#3  2020      1    17
#4  2018      1    35
#5  2019      1    35
#6  2020      1    35

Or in base R use expand.grid with do.call :

do.call(expand.grid, my_list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM