Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subsetting a list object based on a logical statement

Tags:

r

lapply

I am trying to subset some vectors based on a condition. Subsetting them individually gives me different behaviour (the right one) than running the subset on a list containing them. It might be an easy thing that I can't notice.

Subsetting individually:

a<-1:10
b<-11:20
a[a==5]<-0
a

That gives:

> a
 [1]  1  2  3  4  0  6  7  8  9 10

Subsetting while in a list using lapply and same subsetting technique as a function (i.e. x[x==5]<-0) :

a<-1:10
b<-11:20
w<-list(a,b)
q<-lapply(w, function(x){x[x==5]<-0})
q

That gives:

> q
[[1]]
[1] 0

[[2]]
[1] 0
like image 797
mallet Avatar asked Apr 30 '26 23:04

mallet


1 Answers

As @RichardScriven notes in the comments, you need to return x in your lapply function. When you write a function, the return value is either specified explicitly (via return(...)) or is taken to be the last statement executed.

As you have written it, your function is executes the following:

lapply(w, function(x) {
  x <- x[x==5] # subsets a single element
  return(x <- 0) # returns only a single element
}

Instead, you wish to change only one element in the container (vector) and then return the whole container:

lapply(w, function(x) {
  x[x==5] <- 0 # modify only a single element
  return(x) # return the whole vector
}
like image 99
Alex W Avatar answered May 03 '26 12:05

Alex W