apply function for multiple fixed parameter in R

Viewed 178

I have created a function, say myfunc, which has 4 parameters, say para1, para2, para3 and para4. In my problem, para1 is a matrix, para2 is a real number, para3 is a vector, and para4 is a real number. The function returns a list. I have defined the function in the following manner :

myfunc <- function(para1, para2, para3 = NULL, para4 = 100){
          Body ## Body of the function
          return(list("A" = a, "B" = b, "C" = c)
          }

Now, let lambda <- c(2,3,6,10). I am trying to write a code so that the function outputs the following :

myfunc(my_data, 2, my_vec, 100)
myfunc(my_data, 3, my_vec, 100)
myfunc(my_data, 6, my_vec, 100)
myfunc(my_data, 10, my_vec, 100)

This can be easily done by a for loop, but I was thinking if we can use apply or sapply or tapply function for this purpose. So, keeping the other parameters fixed, I want outputs of the same function with different values (viz. the values in lambda) of para2. Can this be done ?


I found a quite similar question here, and saw some answers. I followed those answers, but I'm getting an error. I wrote the following code :

myfunc <- function(para1, para2, para3 = NULL, para4 = 100) { Body }
para1 <- my_data
para3 <- my_vec
para4 <- 100
lambda <- c(2,3,6,10)

sapply(lambda, myfunc, para1=para1, para3, para4=para4)

Can I please get some assistance ? Thanks in advance.

1 Answers

We can use lapply to loop over the lambda

lapply(lambda, function(x) myfunc(my_data, x, my_vec, 100))

If we are not using lambda function

lapply(lamdba, myfunc, para1 = my_data, para3 = my_ec, para4 = 100)
Related