Count values separated by a comma in a character string

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

Leave a Comment