[R] lapply returns NULL ?

ce zadig_1 at excite.com
Sat Jul 12 17:11:33 CEST 2014


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:
>
>
>On 12.07.2014 15:25, ce wrote:
>>
>>
>> Dear all,
>>
>> I have a list of arrays :
>>
>> foo<-list(A = c(1,3), B =c(1, 2), C = c(3, 1))
>>
>>> foo
>> $A
>> [1] 1 3
>>
>> $B
>> [1] 1 2
>>
>> $C
>> [1] 3 1
>>
>>> if( foo$C[1] == 1 ) foo$C[1]
>>
>>>   lapply(foo, function(x) if(x[1] == 1 )  x  )
>>
>> $A
>> [1] 1 3
>>
>> $B
>> [1] 1 2
>>
>> $C
>> NULL
>>
>> I don't want to list $C NULL  in the output. How I can do that ?
>
>Either use your own print function or, if you do not want NULL elements
>
>in the object, remove them.
>
>Best,
>Uwe Ligges
>
>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>______________________________________________
>R-help at r-project.org mailing list
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list