0

Below, I expected that length(group.name) would return 3. But it just returns 1. Is there a Base R solution to get the number of elements of a character vector?

group.name = c("bigii, ggigi, ciggi")
length(group.name)
#[1] 1
rnorouzian
  • 7,397
  • 5
  • 27
  • 72

2 Answers2

1

An option would be to count the words with str_count

library(stringr)
str_count(group.name, "\\w+")
#[1] 3

Or replace all the non-delimiters to blank, use nchar to get the number of characters, add 1 (as the delimiter is 1 less than the number of words)

nchar(gsub("[^,]+", "", group.name)) + 1
#[1] 3

Or using regexpr

lengths(gregexpr("\\w+", group.name))
#[1] 3

It can be turned into a function

f1 <- function(stringObj){

  nchar(gsub("[^,]+", "", stringObj)) + 1
 }

f1(group.name)
#[1] 3
akrun
  • 874,273
  • 37
  • 540
  • 662
0

group.name is a single string. I think you are looking to count every word differently separated by comma, you could do that by splitting on comma and then count it's length

length(strsplit(group.name, ",")[[1]])
#[1] 3
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213