Skip to content

lapply returns NULL ?

2 messages · ce, Luke Tierney

ce
#
Thanks Jeff et. all,

This is exactly what I needed.

-----Original Message-----
From: "Jeff Newmiller" [jdnewmil at dcn.davis.CA.us]
Date: 07/12/2014 10:38 AM
To: "Uwe Ligges" <ligges at statistik.tu-dortmund.de>, "ce" <zadig_1 at excite.com>, r-help at r-project.org
Subject: Re: [R] lapply returns NULL ?

I think that removing them is something the OP doesn't understand how to do.

The lapply function ALWAYS produces an output element for every input element. If this is not what you want then you need to choose a looping structure that is not so tightly linked to the input, such as a for loop (untested):

result <- list()
for (nm in names(foo)) {
  if ( 1 == foo[[nm]][1] ) {
    result[[ nm ]] <- foo[[ nm ]]
  }
}
result

or use vector indexing (lists are a special kind of vector) with the loop result:

foo[ sapply(foo,function(v){1==v[1]}) ]

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.
On July 12, 2014 6:37:44 AM PDT, Uwe Ligges <ligges at statistik.tu-dortmund.de> wrote:
#
Another option is

Filter(function(x) x[1] == 1, foo)

Best,

luke
On Sat, 12 Jul 2014, ce wrote: