Search code examples
rlapplysapplymapplymultiple-arguments

Apply a multi-argument function to a vector, varying only one argument


I would like to apply a function to a vector. My function takes multiple arguments, but I can keep the arguments the same throughout.

Here's what I've come up with, but it doesn't work. I've seen some things using mapply -- I'm not sure if that's what I need though.

add = function(x, y) x+y
sapply(1:5, add(y = 10))

Solution

  • In general you can give additional arguments of a function to sapply like this.

    sapply(1:5, add, y=10)
    

    Just write the function name and after that you can give any number of arguments directly within sapply itself