Bury Bury - 1 year ago 101
R Question

Count values separated by a comma in a character string

I have this example data


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
, but it says 1

After looking for solution here I have tried


But it still doesn't work.

Any straightforward approach to solve this problem?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download