I have a table in R studio and in the third column, I need to paste the number of words of column two using for and while loop. I have no idea how to do it, can someone help?
Asked
Active
Viewed 122 times
1 Answers
0
Try this...
I've created a sample dataframe (but it's always helpful if you include a reproducible example).
some_nums <- c("2","100","16","999", "65")
the_words <- c("some words", "these are some more words", "and these are even more words too", "now fewer words", "I do not even want to try and count the number of words here so why not just let our code figure it out")
my_df <- data.frame(some_nums, the_words,stringsAsFactors = FALSE)
The output is this:
some_nums the_words
1 2 some words
2 100 these are some more words
3 16 and these are even more words too
4 999 now fewer words
5 65 I do not even want to try and count the number of words here so why not just let our code figure it out
Now we just need to count the number of words by applying a string split function to each of the strings in the desired column of our dataframe. This can be done by using the space inbetween the words as our delimiter, or the thing that separates each word. We can also insert these values into a new column in the same step quite easily using the code below.
my_df[["number_of_words"]] <- sapply(strsplit(my_df$the_words, " "), length)
Giving us the following output:
some_nums the_words number_of_words
1 2 some words 2
2 100 these are some more words 5
3 16 and these are even more words too 7
4 999 now fewer words 3
5 65 I do not even want to try and count the number of words here so why not just let our code figure it out 24
I hope this helps.

jimiclapton
- 775
- 3
- 14
- 42
-
Oh my god, thanks so much! This helps a lot actually. I'm very new to all this haha so your help is a lifesaver! – User2111 Apr 29 '20 at 15:01
-
You're very welcome! Know what's it like to be looking for a solution so happy to help. Please consider selecting this as the answer by clicking the check mark. Happy coding! – jimiclapton Apr 29 '20 at 15:03