I have a data frame with words in every row. Example of some rows:
df
This is a word
Another word
third word
word
And I want to count the number of each row and write it to a new data frame and have in a final csv something like this:
df,total
This is a word,4
Another word,2
third word,2
word,1
Possible using the space character?
You can use str_count
library(stringr)
df$total <- str_count(df$df, '\\s+')+1
df$total
#[1] 4 2 2 1
Or
nchar(gsub('[^ ]+', '',df$df))+1
#[1] 4 2 2 1
Or
lengths(strsplit(df$df, '\\S+'))
#[1] 4 2 2 1
Or
count.fields(textConnection(df$df))
#[1] 4 2 2 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With