I’m having a fundamental problem with how the lapply function works. I want to classify each member of each vector in a list.
My list:
s <- list(
a = c(1, 20, 300),
b = c(1.1, 20.1, 300.1),
c = c(1.2, 20.2, 300.3)
)
My classification function:
classify <- function(n, peaks){
which(abs(peaks-n)==min(abs(peaks-n)))
}
My peaks:
peaks <- c(1.27350, 20.32662, 300.02650)
If I classify s$c by itself, I get the result I expect:
> sapply(s$c,classify,peaks)
[1] 1 2 3
But when I try to classify all the vectors at once, I get this:
> lapply(s,classify,peaks)
$a
[1] 3 //should be 1,2,3
$b
[1] 3 //should be 1,2,3
$c
[1] 1 //should be 1,2,3
Why am I getting the result that I do? And how do I get the result that I want?
First, a style point: use
which.minfor finding the location of a minimum.Second, break your code down a bit do see what is happening.
These indicies are what gets returned from the call to
lapply.Based on your comment, I guess your problem is that
lapplyacts on each element of a vector, when you really want to call just call it once on everything, sinceclassifyis already vectorised. Try this: