R 我们如何根据“,”将一列分隔为多列|&引用;?
我有一张桌子R 我们如何根据“,”将一列分隔为多列|&引用;?,r,tidyverse,R,Tidyverse,我有一张桌子 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
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
然而,它在每个字母后都被分开
我想你没有把
包括在中:
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"))
df%tidyr::分离(流派,分为=c(“流派1”、“流派2”、“流派3”),
“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
#一个tible:4 x 6
id genre1 genre2 genre3 genre4 genre5
*
1动作冒险科幻惊悚片
冒险科幻惊悚片
3动作犯罪惊悚片
4家庭动画冒险喜剧动作
编辑:或者正如RichScriven在评论中所写的那样,df%>%tidyr::separate(流派,into=paste0(“流派”,1:5))
。要准确地在
上分离,请使用sep=“\\\\\”
我想您没有将包含在中:
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"))
df%tidyr::分离(流派,分为=c(“流派1”、“流派2”、“流派3”),
“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
#一个tible:4 x 6
id genre1 genre2 genre3 genre4 genre5
*
1动作冒险科幻惊悚片
冒险科幻惊悚片
3动作犯罪惊悚片
4家庭动画冒险喜剧动作
编辑:或者正如RichScriven在评论中所写的那样,df%>%tidyr::separate(流派,into=paste0(“流派”,1:5))
。要准确地在
上分离,请使用sep=“\\\\\”
好吧,正确地编写正则表达式有帮助
df %>%
separate(genres, into = paste0("genre", 1:5), sep = "\\|")
这就是正确编写正则表达式的原因
df %>%
separate(genres, into = paste0("genre", 1:5), sep = "\\|")
使用cSplit
fromsplitstackshape
package,cSplit(df,“genres”和“|”)
。请包括进行拆分的代码。使用cSplit
fromsplitstackshape
package,cSplit(df,“genres”,“genres”,“|”)
。请包括进行拆分的代码。或into=paste0(“genre”,1:5)
@RichScriven更好@对不起,我的代码不完整,我已经做了编辑。您提供的代码将科学和小说拆分为单独的列,这不是我想要的。我希望科幻小说在同一个专栏中,并且只基于“|”的分离@arjan hada啊,好的。为了让它更清晰,我在中添加了它。或者,into=paste0(“流派”,1:5)
@RichScriven更好@对不起,我的代码不完整,我已经做了编辑。您提供的代码将科学和小说拆分为单独的列,这不是我想要的。我希望科幻小说在同一个专栏中,并且只基于“|”的分离@arjan hada啊,好的。我把它加进去是为了更清楚。