tags:

views:

268

answers:

2

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.

+3  A: 
Dirk Eddelbuettel
The first way you did it is what I want. Let me go try that.
Farrel
Yip, it worked. Fantastic. In fact sapply worked even better because it made a simple single vector which I can now go and cbind onto a preexisting dataframe. Now can you explain to me how lapply(name.of.list,length()) and lapply(name.of.list,function(x) length(x)) are different.
Farrel
Please see the additional edit at my answer -- in essence `length` is different from `length()` and you want the former.
Dirk Eddelbuettel
A: 

The code below accepts a list and returns a vector of lengths:

x = c("vectors", "matrices", "arrays", "factors", "dataframes", "formulas", 
      "shingles", "datesandtimes", "connections", "lists")
xl = list(x)
fnx = function(xl){length(unlist(strsplit(x, "")))}
lv = sapply(x, fnx)
doug