list 从 R 中的列表过滤值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14771029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter values from list in R
提问by chriga
I want to calculate the mean of a list of named numbers. There are numeric(0)
values that I first want to remove. Also, I would like to retrieve which elements of the list contain numeric(0)
values.
我想计算命名数字列表的平均值。numeric(0)
我首先要删除一些值。另外,我想检索列表的哪些元素包含numeric(0)
值。
Here is an example how the values could look like:
以下是这些值的外观示例:
>r["gg",]
$`01_1_er`
gg
0.5176445
$`02_1_er`
gg
0.4990959
$`03_1_er`
gg
0.5691489
$`22_1_er`
numeric(0)
$`23_1_er`
numeric(0)
$`25_1_er`
gg
0.386304
And here is the result of str:
这是 str 的结果:
> str(r["gg",])
List of 6
$ 01_1_er: Named num 0.518
..- attr(*, "names")= chr "gg"
$ 02_1_er: Named num 0.499
..- attr(*, "names")= chr "gg"
$ 03_1_er: Named num 0.569
..- attr(*, "names")= chr "gg"
$ 22_1_er: num(0)
$ 23_1_er: num(0)
$ 25_1_er: Named num 0.386
..- attr(*, "names")= chr "gg"
Can anyone help?
任何人都可以帮忙吗?
回答by juba
## Example list
l <- list(n1=numeric(0), n2="foo", n3=numeric(0), n4=1:5)
## Filter out elements with length 0
l[lapply(l, length) > 0]
$n2
[1] "foo"
$n4
[1] 1 2 3 4 5
## Get names of elements with length 0
names(l)[lapply(l, length) == 0]
[1] "n1" "n3"
回答by Ramnath
回答by James
Unlisting will pull out just the numeric entries in a single vector which you can call mean on, so try:
取消列出将仅提取单个向量中的数字条目,您可以调用平均值,因此请尝试:
mean(unlist(r["gg",]))