[R] how to update a value in a list with lapply

David Winsemius dwinsemius at comcast.net
Sun May 10 02:00:20 CEST 2015


On May 9, 2015, at 4:35 PM, ce wrote:

> Dear All,
> 
> I have a list, using lapply I find some elements of the list, and then I want to change the values I find. but it doesn't work:
> 
> foo<-list(A = c(1,3), B =c(1, 2), C = c(3, 1))
> lapply(foo, function(x) if(x[1] == 1 ) x )
> $A
> [1] 1 3
> 
> $B
> [1] 1 2
> 
> $C
> NULL
> 
> lapply(foo, function(x) if(x[1] == 1 ) x[2] <- 0 )
> $A
> [1] 0
> 
> $B
> [1] 0
> 
> $C
> NULL
> 
>> lapply(foo, function(x) if(x[1] == 1 ) x )
> $A
> [1] 1 3
> 
> $B
> [1] 1 2
> 
> $C
> NULL
> 
> 
> how to do it correctly ?

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).

-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list