计算字符串中以逗号分隔的值 [英] Count values separated by a comma in a character string

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

问题描述

我有这个示例数据

d<-"30,3"
class(d)

我在工作数据框中的一列中有这个字符对象,我需要能够识别它有多少个数字.

I have this character objects in one column in my work data frame and I need to be able to identify how many numbers it has.

我尝试使用 length(d),但它说 1

I have tried to use length(d), but it says 1

在这里寻找解决方案后,我尝试过

After looking for solution here I have tried

eval(parse(text='d'))
as.numeric(d)
as.vector.character(d)

但是还是不行.

有什么简单的方法可以解决这个问题?

Any straightforward approach to solve this problem?

推荐答案

这两种方法都很短,适用于字符串向量,不涉及显式构造拆分字符串的费用,也不使用任何包.这里 d 是一个字符串向量,例如 d <- c("1,2,3", "5,2") :

These two approaches are each short, work on vectors of strings, do not involve the expense of explicitly constructing the split string and do not use any packages. Here d is a vector of strings such as d <- c("1,2,3", "5,2") :

1) count.fields

count.fields(textConnection(d), sep = ",")

2) gregexpr

lengths(gregexpr(",", d)) + 1

这篇关于计算字符串中以逗号分隔的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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