从R中的列表中筛选值

时间:2021-10-20 01:34:58

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.

我想计算一个命名数字列表的平均值。我首先要删除数字(0)值。此外,我想检索列表中的哪些元素包含数字(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?

有人可以帮忙吗?

3 个解决方案

#1


19  

## 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"

#2


2  

Unlisting will pull out just the numeric entries in a single vector which you can call mean on, so try:

Unlisting将仅提取单个向量中的数字条目,您可以将其称为mean on,请尝试:

mean(unlist(r["gg",]))

#3


2  

Another solution

另一解决方案

mean(unlist(Filter(is.numeric, l)))

#1


19  

## 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"

#2


2  

Unlisting will pull out just the numeric entries in a single vector which you can call mean on, so try:

Unlisting将仅提取单个向量中的数字条目,您可以将其称为mean on,请尝试:

mean(unlist(r["gg",]))

#3


2  

Another solution

另一解决方案

mean(unlist(Filter(is.numeric, l)))