nes1983
nes1983

Reputation: 15756

In R, how can you plug a list into a function that accepts two arguments?

I have a function f that accepts two arguments, a and b. I have a list of values x that I'd like to plug in for a, while b is fixed. In Ruby, I'd use map, as in:

 x.map {|el| f(el,3) } 

How do you write this in R?

Upvotes: 2

Views: 260

Answers (3)

Ben Bolker
Ben Bolker

Reputation: 226192

edited: fixed argument order

Something like lapply(x,f,b=3) (or sapply())

Upvotes: 5

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32351

Depending on your function, you can sometimes use it directly, with a vector as first argument

f <- function(a,b) a+b
f(1:10,2)

or, if it does not work (if the function assumes that the first argument is a single number, as opposed to a vector), you can vectorize it (Vectorize just hides the call to lapply).

f <- Vectorize(f)
f(1:10,2)

Upvotes: 4

Tommy
Tommy

Reputation: 40821

In this case sapply works fine (as @BenBolker answered), but mapply is also a good alternative, and actually the "best" solution when both a and b varies:

f <- function(a,b) a+b
x <- as.list(11:13) # you said you had a list...

# One argument (b) is fixed
sapply(x, f, 3) # 14 15 16
mapply(f, x, 3) # 14 15 16

# Both arguments vary
y <- 101:103
mapply(f, x, y) # 112 114 116

Upvotes: 3

Related Questions