splitting text in column and add row number [duplicate]

无人久伴 提交于 2019-12-02 07:05:44

I'm biased in favor of cSplit from the "splitstackshape" package, but you might be interested in unnest from "tidyr" in conjunction with "dplyr":

library(dplyr)
library(tidyr)
df %>%
  mutate(b = strsplit(b, ";")) %>%
  unnest(b)
#   a b
# 1 1 g
# 2 1 j
# 3 1 n
# 4 2 x
# 5 2 f
# 6 2 v

You could do this using cSplit from splitstackshape

library(splitstackshape)
cSplit(df, 'b', ';', 'long')
#   a b
#1: 1 g
#2: 1 j
#3: 1 n
#4: 2 x
#5: 2 f
#6: 2 v

Or using dplyr/tidyr

library(dplyr)
library(tidyr)
separate(df, b, c('b1', 'b2', 'b3'), sep=";") %>%
                               gather(Var, b, -a) %>% 
                               select(-Var) %>% 
                               arrange(a)

Or another option would be to use do

df %>%
   group_by(a) %>% 
   do(data.frame(b=unlist(strsplit(.$b, ';'))))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!