Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter values from list in R

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.

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(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?

like image 488
chriga Avatar asked Feb 08 '13 10:02

chriga


2 Answers

## 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"
like image 90
juba Avatar answered Oct 15 '22 21:10

juba


Another solution using the Filter function from base R:

mean(unlist(Filter(is.numeric, l)))
like image 41
Ramnath Avatar answered Oct 15 '22 20:10

Ramnath