r - dplyr split string into a comma separated list -


i'm trying use dplyr split string comma separated string , i'm not having luck.

dat<-data.frame(key=1:4,labels=c('a','ab','abc','b')) 

i'm trying labels column c('a','a,b','a,b,c','b')

i've tried of below variations nothing seems work.

dat %>%   mutate(labels=str_split(labels,''))  dat %>%   mutate(labels=str_split(labels,'')[[1]])  dat %>%   mutate(labels=paste(str_split(labels,''),collapse=',')) 

dplyr or mutate has nothing question. problems more along lines of trying treat list (returned str_split) vector.

i write little function it:

comma_sep = function(x) {     x = strsplit(as.character(x), "")     unlist(lapply(x, paste, collapse = ',')) } 

you can

mutate(dat, labels = comma_sep(labels)) #   key labels # 1   1      # 2   2    a,b # 3   3  a,b,c # 4   4      b 

but of course jam meat of function 1 line well.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo