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

3 Answers 3

1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Arguably don't use subset either... lapply( list , function(x) x[ x > 5 ] )
@SimonO101 Yes, definitely.
0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.