0

I have a data.frame named df with one column named Text, consisting of some sentences, and I want to add a new column named Length equal to number of words in the Text column. So, my data.frame looks like this:

      Text
1. First sentence.
2. Second sentence that is a bit longer.
3. Third.
4. Fourth one is the longest one with 9 words.

And the desired data.frame should look like this:

      Text                                  Length
1. First sentence.                              2
2. Second sentence that is a bit longer.        7
3. Third.                                       1
4. Fourth one is the longest one with 9 words.  9

These are my tries:

df$Length <- length(do.call(strsplit(., " ")[[1]], as.list(df$Text)))

and

df$Length <- do.call(length(strsplit(., " ")[[1]]), as.list(df$Text))

Would you please help me understanding what should I do?

Mehdi Abbassi
  • 627
  • 1
  • 7
  • 24

1 Answers1

2

You could also user the purrr-package:

df %>%
 dplyr::mutate(Length = purrr::map_dbl(Text, ~ length(unlist(stringr::str_split(as.character(.), " ")))))
Florian
  • 1,248
  • 7
  • 21