Reputation: 187
In a dataframe like this:
data.frame(id = c(1,2), alternativenum = c(342, 5921), text = c("one text here","another text here also"))
How is it possible to add a new column in this dataframe where it will contain a word counter for every row using the text column?
Example of expected output
data.frame(id = c(1,2), alternativenum = c(342, 5921), text = c("one text here","another text here also"), counter = c(3, 4))
The separator is always the blank space between words
Upvotes: 0
Views: 454
Reputation: 1513
You can use str_count()
from the stringr
package to count the number of words using the \\w+
escape pattern.
df <- data.frame(
id = c(1,2),
alternativenum = c(342, 5921),
text = c("one text here","another text here also"),
stringsAsFactors = FALSE)
library(stringr)
library(dplyr)
df %>%
mutate(counter = str_count(df$text, pattern = "\\w+"))
id alternativenum text counter
1 1 342 one text here 3
2 2 5921 another text here also 4
Upvotes: 1