tadeufontes
tadeufontes

Reputation: 477

How to use lapply only for one specific argument of a function?

So I have a function that takes more than one argument and I want to use apply for just values of one of the arguments. I'll use an example:

v<-c("a","b","c","d")

f<-function(arg1,arg2,arg3,arg4){
}

I tried using this line of code, because I only want to use the "arg2":

x<-lapply(v,f(),arg2=arg2)

Unfortunately I got the error:

Error in check_args_given_nonempty(args, c("arg1", "arg2", "arg3", "arg4", : You must provide a non-empty value to at least one of arg1 arg2 arg3 arg4

Thanks in advance for any answers

Upvotes: 1

Views: 524

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269461

1) Specify the fixed arguments like this:

f <- function(x1, x2, x3, x4) paste(x1, x2, x3, x4)
lapply(1:5, f, x1 = "a", x3 = "c", x4 = "d")

giving

[[1]]
[1] "a 1 c d"

[[2]]
[1] "a 2 c d"

[[3]]
[1] "a 3 c d"

[[4]]
[1] "a 4 c d"

[[5]]
[1] "a 5 c d"

2) or wrap it into a one-argument function:

lapply(1:5, function(x) f("a", x, "c", "d"))

3) There are also a number of packages that will accept a function as input and output a function with some of the arguments fixed, known as currying. Here are two different packages that can curry a function.

library(purrr)
lapply(1:5, partial(f, list(x1 = "a", x3 = "c", x4 = "d")))

library(functional)
lapply(1:5, Curry(f, x1 = "a", x3 = "c", x4 = "d"))

Upvotes: 1

Related Questions