Can lapply pass (to a function) values stored in a vector, successively

浪子不回头ぞ 提交于 2019-12-04 03:37:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!