Luke_radio
Luke_radio

Reputation: 977

lapply to turn specified matrix elements within list to NA

I have a list of matrices (toy example):

x <- matrix(1:20, nrow = 2, ncol = 10)
y <- matrix(1:20, nrow = 2, ncol = 10)

l <- list(x ,y)

I need to turn some elements >= 11 into NA.

Outside of the list I would just use

x[(x>= 11)] <- NA

but trying to lapply the same function appears to apply it to each matrix as a whole (ie each matrix turns into a single NA value).

l_na <- lapply(l, function(x) x[(x >= 11)] <- NA)

I'm clearly misunderstanding something about lapply. A solution and any pointers of what I am getting wrong here would be appreciated.

Upvotes: 0

Views: 112

Answers (2)

akrun
akrun

Reputation: 887048

We can use replace

l_na <- lapply(l, function(x) replace(x, x>=11, NA))
l_na
#[[1]]
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#[1,]    1    3    5    7    9   NA   NA   NA   NA    NA
#[2,]    2    4    6    8   10   NA   NA   NA   NA    NA

#[[2]]
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#[1,]    1    3    5    7    9   NA   NA   NA   NA    NA
#[2,]    2    4    6    8   10   NA   NA   NA   NA    NA

Or with some golfing

lapply(l, function(x) x*NA^(x>=11))

Upvotes: 3

steveb
steveb

Reputation: 5532

This works

l_na <- lapply(l, function(x) { x[(x >= 11)] <- NA; x })
l_na

##[[1]]
##     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
##[1,]    1    3    5    7    9   NA   NA   NA   NA    NA
##[2,]    2    4    6    8   10   NA   NA   NA   NA    NA
##
##[[2]]
##     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
##[1,]    1    3    5    7    9   NA   NA   NA   NA    NA
##[2,]    2    4    6    8   10   NA   NA   NA   NA    NA

Adding the x as a return value like above is one option. I don't know if there are others.

Upvotes: 3

Related Questions