Getting r to output how many 1, 2, 3 etc letter words per array

Viewed 34

I need to create an array with counts of how many times a word with one, two, three, ... etc., letters appears in each sentences. That is, the array with 4 columns (one column per sentence) and 9 rows (1 letter, 2 letters, etc.)

This is what I have so far:

text <- c("Take a vector below", 
          "Assume that you start summation from the first element adding element by element", 
          "Your task is to find the maximal number of elements you can take",
          "while the total summation stays below some given threshold")

words <- strsplit(text, split = " ") 
1 Answers

To get the word length for each sentence, try this:

nwords <- sapply(words, length)
sentence <- rep(1:4, nwords)
wordlength <- unlist(sapply(words, nchar))
table(wordlength, sentence)
#       sentence
# wordlength 1 2 3 4
#          1 1 0 0 0
#          2 0 1 3 0
#          3 0 2 3 1
#          4 1 2 4 1
#          5 1 2 0 5
#          6 1 2 1 0
#          7 0 3 1 0
#          8 0 0 1 0
#          9 0 1 0 2
Related