问题
I need lapply to pass (to a function) values stored in a vector, successively.
values <- c(10,11,13,10)
lapply(foo,function(x) peakabif(x,npeaks=values))
So to get :
peakabif(x1,npeaks=10)
peakabif(x2,npeaks=11)
peakabif(x3,npeaks=13)
peakabif(x4,npeaks=10)
Is this possible or do I need to reconsider using lapply ? Is a for loop inside the function would work ?
回答1:
You want to use mapply
for this: mapply(peakabif, x=foo, npeaks=values)
回答2:
There are a couple of ways to handle this. You could try a straight indexing vector approach.
lapply(1:length(foo), function(i) peakabif(foo[i], npeaks=values[i]))
(and someone already beat me to the mapply version...)
回答3:
Sometimes you can convert an existing function so that it will accept vectors (or lists) using Vectorize
vrep <- Vectorize(rep.int)
> vrep(list(1:4, 1:5), list(2,3) )
[[1]]
[1] 1 2 3 4 1 2 3 4
[[2]]
[1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
(Under the hood it's really a convenience wrapper for mapply
in the same way the read.table
is a wrapper for scan
.)
来源:https://stackoverflow.com/questions/14265720/can-lapply-pass-to-a-function-values-stored-in-a-vector-successively