0

I want to count the number of words in a text my data.

Then

I want to use a loop to count the number of words in a specific column "Opinion" for every row in my data.

Any suggestions?

Joe Bens
  • 29
  • 1
  • 5

1 Answers1

4

We can use str_count from stringr

library(stringr)
df1$nwords <- str_count(df1$Opinion, "\\w+")

Or using a for loop

df1$nwords <- NA_integer_
for(i in seq_along(df1$Opinion)) {
      df1$nwords[i] <- length(strsplit(df1$Opinion[i], "\\s+")[[1]])
 }

Or with strsplit on the whole column

df1$nwords <- lengths(strsplit(df1$Opinion, "\\s+"))
akrun
  • 874,273
  • 37
  • 540
  • 662