1

What's the right approach to using Map for a function with two arguments in R?

I could get the same effect by using a function which takes 1 argument that consists of a list, and then pass in a list of lists, but I'd like to know if there's a better solution.

2 Answers 2

2

Just feed in the extra arguments as a vector like mapply.

Map('+', 1:5, 2:6)

You can name them if you want. If they're not long enough they're recycled out to the right length (e.g. n here)

Map(rnorm, n=1, mean=1:5, sd=1:5)
Sign up to request clarification or add additional context in comments.

Comments

1

Since mapply(f, c(a,b,c,...)) = c(f(a), f(b), f(c), ...), it is unclear what those extra arguments should be. If the additional arguments are fixed (or are derived from the element itself), you can use an anonymous function: mapply(function(x) g(1, true, x, 42), c(a,b,c,...)).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.