Skip to content
Prev 350803 / 398502 Next

how to update a value in a list with lapply

ce
yes indeed :

 foo <- lapply(foo, function(x) if(x[1] == 1 ) {x[2] <- 0; x }else{x} )

would work. But if the list is too long, would it be time consuming  rather than just updating elements that meet the if condition?

thx
ce


-----Original Message-----
From: "David Winsemius" [dwinsemius at comcast.net]
Date: 05/09/2015 08:00 PM
To: "ce" <zadig_1 at excite.com>
CC: r-help at r-project.org
Subject: Re: [R] how to update a value in a list with lapply
On May 9, 2015, at 4:35 PM, ce wrote:

            
I find it useful to think of the `if` function as `if(cond){cons}else{alt}`

lapply(foo, function(x)  if(x[1] == 1 ) {x[2] <- 0; x }else{x} )
#-----
$A
[1] 1 0

$B
[1] 1 0

$C
[1] 3 1


You were not supply an alternative which was the cause of the NULL (and you were not returning a value which meant that the value returned was the value on the RHS of the assignment).