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
Use
lapplyandifelse: