2017-06-16 46 views
0

我有一个tibble。我们如何一列分为基于多个的“|”?

library(tidyverse) 
df <- tibble(
    id = 1:4, 
    genres = c("Action|Adventure|Science Fiction|Thriller", 
     "Adventure|Science Fiction|Thriller", 
     "Action|Crime|Thriller", 
     "Family|Animation|Adventure|Comedy|Action") 
) 
df 

enter image description here

我想通过流派分开 “|”和填充NA的空列。

这是我做过什么:

df %>% 
    separate(genres, into = c("genre1", "genre2", "genre3", "genre4", "genre5"), sep = "|") 

然而,每个字母后它被分离。

enter image description here

+0

使用'cSplit'从'splitstackshape'包,'CSPLIT(DF, “流派”, “|”)'。 –

+0

请包含拆分的代码。 – neilfws

回答

2

我想你还没有包括into

df <- tibble::tibble(
    id = 1:4, 
    genres = c("Action|Adventure|Science Fiction|Thriller", 
      "Adventure|Science Fiction|Thriller", 
      "Action|Crime|Thriller", 
      "Family|Animation|Adventure|Comedy|Action") 
) 
df %>% tidyr::separate(genres, into = c("genre1", "genre2", "genre3", 
       "genre4", "genre5")) 

结果:

# A tibble: 4 x 6 
    id genre1 genre2 genre3 genre4 genre5 
* <int>  <chr>  <chr>  <chr> <chr> <chr> 
1  1 Action Adventure Science Fiction Thriller 
2  2 Adventure Science Fiction Thriller  <NA> 
3  3 Action  Crime Thriller  <NA>  <NA> 
4  4 Family Animation Adventure Comedy Action 

编辑:或者像RichScriven在评论中,df %>% tidyr::separate(genres, into = paste0("genre", 1:5))写道。有关|分离准确,使用sep = "\\|"

+2

或'到= paste0( “流派”,1:5)' –

+0

@RichScriven更加美好! – RobertMc

+0

@ RobertMc-对不起我的不完整的代码,我进行了编辑。你提供的代码将科学和小说分成不同的列,这不是我想要的。我希望“科幻小说”只在“|”的基础上进行同一列和分隔。 –

0

那么,这是什么样的帮助下,正确书写正则表达式。

df %>% 
    separate(genres, into = paste0("genre", 1:5), sep = "\\|") 
相关问题