Reputation: 275
require(plyr)
list <- list(a=c(1:3),
b=c(1:5),
c=c(1:8),
d=c(1:10))
llply(list,function(x)(subset(x,subset=(x>5))))
The above returns:
$a
integer(0)
$b
integer(0)
$c
[1] 6 7 8
$d
[1] 6 7 8 9 10
How to return a list only with the existing values, here $c and $d?
Upvotes: 0
Views: 540
Reputation: 11
You can use 'lengths()':
# Your original list
your_list1 <- list(a=c(1:3),
b=c(1:5),
c=c(1:8),
d=c(1:10))
# Your subseted list
your_list2 <- lapply(your_list1,function(x) x[ x > 5 ])
# Your 'non_empty_elements' list
your_final_list <- your_list2[(lengths(your_list2) > 0)]
> your_final_list
$c
[1] 6 7 8
$d
[1] 6 7 8 9 10
Pdt: Names assigned to objets that you create must make sense to you, but I agree Stephen Henderson that it's not a good practice to use a functions' name for objects. I think it is not necessary either, to use such long names as I have, except for pedagogical reasons.
Upvotes: 0
Reputation: 44527
You don't need plyr for this:
out <- lapply(list, function(x) x[ x > 5 ] )
out[ sapply(out, length) > 0 ]
Result:
$c
[1] 6 7 8
$d
[1] 6 7 8 9 10
Upvotes: 1
Reputation: 6522
You really shouldn't call a list variable "list" as it's a function name. If it's called L then:
L[lapply(L,length)>0]
this should give a nonempty list
Upvotes: 0