1

My sample dataset looks like below. I need to calculate the number of characters.

keyword <- c("advertising",
         "advertising budget",
         "marketing plan detail",
         "marketing budget and forecast")

I tried the "nchar" function, but it actually calculates the number of digits. For this sample, the results should be 1,2,3,4.

Ran Tao
  • 311
  • 1
  • 4
  • 13

2 Answers2

2

One option is str_count and specify the patterns for word (\\w+)

library(stringr)
str_count(keyword, "\\w+")
#[1] 1 2 3 4

Or with base R

lengths(gregexpr("\\w+", keyword))
#[1] 1 2 3 4
akrun
  • 874,273
  • 37
  • 540
  • 662
1
unlist( lapply(strsplit(keyword, split = "\ "), length) )
[1] 1 2 3 4
Sathish
  • 12,453
  • 3
  • 41
  • 59