Reputation: 57
How do I calculate the average number of words in a list using for loop in r? 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!
Upvotes: 1
Views: 177
Reputation: 887501
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)
Upvotes: 2