I never used Filter before your question, so it was a good exercise for the first thing in the morning :)
There are at least a few things you can turn off (I think).
Let's start with the first simple anonymous function, but let me make it autonomous so that it is easier to read:
f <- function(i){ z[[i]] > 1 }
You should jump out to the fact that this function takes one argument i , but in the function that it calls z . This is not very good "functional" programming :)
So, start by changing this function to:
f <- function(i){ i > 1 }
And you will see that Filter will actually run against the list of lists:
z <- list(z1=list(a=1,b=2,c=3), z2=list(a=1,b=1,c=1)) Filter( f, z)
but it returns:
> Filter( f, z) $z2 $z2$a [1] 1 $z2$b [1] 1 $z2$c [1] 1 $<NA> NULL
which is not exactly what you want. Honestly, I canβt understand why it returns this result, maybe someone can explain it to me.
@DWin barked the right tree when he said there should be a recursive solution. I cracked the first hit with a recursive function, but you need to improve it:
fancyFilter <- function(f, x){ if ( is.list( x[[1]] ) )
fancyFilter looks at the first x element passed to it, and if that element is a list, it recursively calls fancyFilter for each element of the list. But what if item number 2 is not a list? This is what you need to check and tell if it is important to you. But the result of fancyFilter seems similar to what you need:
> fancyFilter(f, z) $z1 $z1$a numeric(0) $z1$b [1] 2 $z1$c [1] 3 $z2 $z2$a numeric(0) $z2$b numeric(0) $z2$c numeric(0)
You can add some logic to clear the output so that the FALSE results are not subjected to harassment of numeric(0) . And, obviously, I made an example using only your simple function, and not the more complex function that you used in the second example.