Davy Kavanagh
Davy Kavanagh

Reputation: 4949

Replacing elements of a multi-level list without a loop

So I have a list, each element of which is a numeric vector. Each number ranges from 0 to 1, and I am interested only in those which are greater than .95, but I must keep their position on the vector, and all the other numbers as I need to plot their positions relative to each other.

l1 = list(c(runif(20)),c(runif(21)),c(runif(22)),c(runif(19)))

so I tried to set all number below 0.95 equal to 0, using lapply like so:

l1 = lapply(l1, function(x){x[x<.95]=0})

but this just returns a list of an equal number of elements as the input list (as one would expect), but each element is simply zero.

so I tried it with a for loop like so:

for(i in 1:length(l1))
{
  l1[[i]][l1[[i]]<.95]=0
}

and that worked. Each element is the same length as the input vector, and contains only 0s and numbers greater that .95

Could someone explain why the lapply didn't work. I'd prefer not to have to use a for loop, as I am led to believe they are slower, and the real data set I am working on is much larger.
As always,
all help is appreciated,
Cheers,
Davy

Upvotes: 1

Views: 369

Answers (2)

nograpes
nograpes

Reputation: 18323

The reason why your code didn't work is because It merely set the x to what you want, but didn't return the value itself. This would fix it:

lapply(l1, function(x) {x[x<.95]=0;x})

I think the ifelse would be more elegant, though.

Upvotes: 2

James
James

Reputation: 66844

Use lapply and ifelse:

lapply(l1,function(x) ifelse(x<0.95,0,x))

Upvotes: 3

Related Questions