1

How do I calculate the average number of words in a list using for loop in ? I have a list called mylist which contains 25 vectors with character quotes on each vector.

Here is my code so far:

count <- 0
for (i in mylist[1:25]){
count <- count + i
mean(count)
}

But I get this error :

Error in count + i : non-numeric argument to binary operator

Any help will be greatly appreciated!

massisenergy
  • 1,764
  • 3
  • 14
  • 25
Pinaypy
  • 37
  • 1
  • 8
  • Please add some sample data and your expected output. – tmfmnk Mar 07 '20 at 18:07
  • Please look at https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and format your question accordingly. – tmfmnk Mar 07 '20 at 18:13
  • This is part of 25 sublists: `[[1]] [1] "A" "coward" "is" "incapable" "of" [6] "exhibiting" "love;" "it" "is" "the" [11] "prerogative" "of" "the" "brave." ` `[[2]] [1] "A" "man" "never" "tells" "you" "anything" [7] "until" "you" "contradict" "him." ` – Pinaypy Mar 07 '20 at 18:28

1 Answers1

2

We can use lengths to get the length of each vector in the list and then wrap with mean

mean(lengths(mylist))

If we need a loop, then create a vector to store the length

v1 <- numeric(length(mylist))
for(i in seq_along(mylist)) v1[i] <- length(mylist[[i]])
mean(v1)
akrun
  • 874,273
  • 37
  • 540
  • 662