dplyr将字符串拆分为逗号分隔列表 [英] dplyr split string into a comma separated list

查看:131
本文介绍了dplyr将字符串拆分为逗号分隔列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用dplyr将一个字符串拆分成逗号分隔的字符串,我没有太多的运气。

I'm trying to use dplyr to split a string into a comma separated string and I'm not having much luck.

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

我试图将标签栏设为c('a','a,b','a,b,c','b')

I'm trying to get the labels column to be c('a','a,b','a,b,c','b')

我尝试过以下所有变体,但似乎没有任何效果。

I've tried all of the below variations but nothing seems to work.

dat %>%
  mutate(labels=str_split(labels,''))

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

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


推荐答案

dplyr mutate 与您的问题无关。您的问题更多的是尝试将列表(由 str_split 返回)作为向量。

dplyr or mutate has nothing to do with your question. Your problems are more along the lines of trying to treat a list (returned by str_split) as a vector.

我会写一个小功能:

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

然后您可以

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

但是,当然,你也可以将该功能的肉块塞进一行。

But of course you could jam the meat of the function into that one line as well.

这篇关于dplyr将字符串拆分为逗号分隔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆