Bury Bury - 4 months ago 9
R Question

Count values separated by a comma in a character string

I have this example data

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.

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)


But it still doesn't work.

Any straightforward approach to solve this problem?

Answer

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

sapply(gregexpr(",", d), length) + 1