This question already has an answer here:
- Count the number of all words in a string 14 answers
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.
Solved
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
unlist( lapply(strsplit(keyword, split = "\ "), length) )
[1] 1 2 3 4
No comments:
Post a Comment