Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the total number of words in of rows of a dataframe

Tags:

r

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?

like image 306
Ster32 Avatar asked Jul 14 '15 05:07

Ster32


1 Answers

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
like image 60
akrun Avatar answered Sep 29 '22 10:09

akrun