I have a list containing 98 items. But each item contains 0, 1, 2, 3, 4 or 5 character strings.
I know how to get the length of the list and in fact someone has asked the question before and got voted down for presumably asking such an easy question.
But I want a vector that is 98 elements long with each element being an integer from 0 to 5 telling me how many character strings there are in each list item.
I was expecting the following to work but it did not.
lapply(name.of.list,length())
From my question you will see that I do not really know the nomeclature of lists and items. Feel free to straighten me out.
Farrel, I do not exactly follow as ‘item’ is not an R type. Maybe you have a
listof length 98 where each element is a vector of character string?In that case, consider this:
So there is you vector of the length of your list, telling you how many strings each list element has. Note the last
do.call(rbind, someList)as we got a list back fromlapply.If, on the other hand, you want to count the length of all the strings at each list position, replace the simple
length(x)with a new function counting the characters:If that is not want you want, maybe you could mock up some example input data?
Edit:: In response to your comments, what you wanted is probably:
Note that I pass in
length, the name of a function, and notlength(), the (displayed) body of a function. Because that is easy to mix up, I simply apply almost always wrap an anonymous function around as in my first answer.And yes, this can also be done with just
sapplyor even some of the**plyfunctions: