`unnest_wider` multiple columns

泪湿孤枕 提交于 2021-01-29 15:53:59

问题


I have a tibble with multiple columns with multiple list columns I'd like to unnest_wider.

df1 <- tibble(
  gr = c('a', 'b', 'c'),
  values1 = list(1:2, 3:4, 5:6),
  values2 = list(1:2, 3:4, 5:6)
)

I have tried many approaches that have not worked including adding a vector into col

df1 %>% # unnest_wider doesn't take multiple inputs
  unnest_wider(col = c(values, values2),
               names_sep = c("_1", "_2"), 
               names_repair = "unique")

and trying mutate_at

df1 %>% # mutate_at doesn't send data
  mutate_at(vars(values, values2), 
            ~unnest_wider(col = .,
               names_sep = c("_1", "_2"), 
               names_repair = "unique"))

How can I unnest multiple columns wider?


回答1:


Here is one option with map

library(dplyr)
library(purrr)
map_dfc(names(df1[-1]), ~ 
        df1 %>% 
             select(.x) %>%
             unnest_wider(c(!!.x), names_sep=c("_1", "_2"), 
                names_repair = 'unique')) %>%
  bind_cols(df1 %>% 
  select(gr), .)
# A tibble: 3 x 5
#  gr    values1_1 values1_2 values2_1 values2_2
#* <chr>     <int>     <int>     <int>     <int>
#1 a             1         2         1         2
#2 b             3         4         3         4
#3 c             5         6         5         6



回答2:


Answer I used

df1 %>% 
  unnest() %>% 
  mutate(q_name = rep(c("1", "2"), nrow(.)/2)) %>% 
  pivot_wider(id_cols = gr, 
              names_from = q_name, 
              values_from = values1:values2)


来源:https://stackoverflow.com/questions/60820415/unnest-wider-multiple-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!