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

后端 未结 3 1265
误落风尘
误落风尘 2021-01-19 18:24

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))
         


        
相关标签:
3条回答
  • 2021-01-19 18:58

    You want to use mapply for this: mapply(peakabif, x=foo, npeaks=values)

    0 讨论(0)
  • 2021-01-19 18:59

    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.)

    0 讨论(0)
  • 2021-01-19 19:00

    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...)

    0 讨论(0)
提交回复
热议问题