生成每个列表项中项数的向量 [英] Generating a vector of the number of items in each list item

查看:37
本文介绍了生成每个列表项中项数的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含98个项目的列表.但是每个项目都包含0、1、2、3、4或5个字符串.

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.

但是我想要一个向量,该向量长98个元素,每个元素是0到5的整数,告诉我每个列表项中有多少个字符串.我原以为下面的方法会起作用,但是没有.

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.

推荐答案

我很不理解,因为'item'不是R类型.也许您有一个长度为98的 list ,其中每个元素都是字符串的向量?

Farrel, I do not exactly follow as 'item' is not an R type. Maybe you have a list of length 98 where each element is a vector of character string?

在这种情况下,请考虑以下问题:

In that case, consider this:

R> fl <- list(A=c("un", "deux"), B=c("one"), C=c("eins", "zwei", "drei"))
R> lapply(fl, function(x) length(x))
$A
[1] 2

$B
[1] 1

$C
[1] 3
R> do.call(rbind, lapply(fl, function(x) length(x)))
  [,1]
A    2
B    1
C    3
R> 

因此,您有一个列表长度的向量,告诉您每个列表元素有多少个字符串.请注意最后一个 do.call(rbind,someList),因为我们从 lapply 返回列表.

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 from lapply.

另一方面,如果您要计算每个列表位置的所有字符串的长度,则用一个新的计算字符数的函数替换简单的 length(x):

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:

R> lapply(fl, function(x) { sapply(x, function(y) nchar(y)) } )
$A
  un deux 
   2    4 

$B
one 
  3 

$C
eins zwei drei 
   4    4    4 

R> 

如果那不是您想要的,也许您可​​以模拟一些示例输入数据?

If that is not want you want, maybe you could mock up some example input data?

:针对您的评论,您想要的可能是:

: In response to your comments, what you wanted is probably:

R> do.call(rbind, lapply(fl, length))
  [,1]
A    2
B    1
C    3
R> 

请注意,我传入的是函数名称 length ,而不是函数的(显示的)主体 length().因为这很容易混淆,所以我几乎总是像在第一个答案中一样,总是套用匿名函数.

Note that I pass in length, the name of a function, and not length(), 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.

是的,这也可以仅通过 sapply 甚至某些 ** ply 函数来完成:

And yes, this can also be done with just sapply or even some of the **ply functions:

R> sapply(fl, length)
A B C 
2 1 3 
R> lapply(fl, length)
[1] 2 1 3
R> 

这篇关于生成每个列表项中项数的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆