将列列拆分为每列的条目

问题描述 投票:1回答:1

我想将列表列元素拆分为单独的列。

例如,在星球数据集中,

data("starwars")

我想要这个列表列(第7行中的条目)

c("Attack of the Clones", "Revenge of the Sith", "A New Hope")

用电影的值分成A,B,C ......列

   A                          B                   C       D    ...
Attack of the Clones   Revenge of the Sith   A New Hope   NA   ...

我有一种黑客攻击方式

starwars %>% separate(films, into= letters[1:7],sep = ",")

这将导致输出

       A                          B                   C             D     ...
c("Attack of the Clones"   "Revenge of the Sith"   "A New Hope")    NA    ...

但这需要一些额外的擦洗,我不认为这是一般的。有没有办法一举做到这一点?

r list dplyr nested tidyr
1个回答
1
投票

'电影'专栏是listvector。如果我们想用7列创建data.frame,即'films'的maximum length并将其存储为list,将length指定为整列的最大长度,将其转换为data.frame

library(tidyverse)
mx <- max(lengths(starwars$films))
starwars %>% 
   mutate(films = map(films, ~ `length<-`(.x, mx) %>% 
                  as.data.frame.list %>% 
                  set_names(LETTERS[seq_len(mx)]))) %>%
   unnest(films)

或者另一种选择是pull的'电影'专栏,将其转换为n tibble内的map,与'starwars'的列绑定,除了'电影'

starwars %>% 
    pull(films) %>% 
    map_df(~ t(.x) %>% 
               as_tibble) %>%
    bind_cols(starwars %>% 
                 select(-films), .)
© www.soinside.com 2019 - 2024. All rights reserved.