2

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.

JRC
  • 161
  • 1
  • 11

1 Answers1

3

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Many thanks! I used the first line that you wrote, and it's working fine! Can you please tell me what you meant by your second line (i.e. "If we are not using lambda function") ? – JRC Jul 14 '21 at 16:35
  • @Kolmogorov I meant the lambda/anonymous fucntion not as `lambda` you defined. It is the `function(x) ..` i.e. the funciton created on the fly without assigning it to a object – akrun Jul 14 '21 at 16:37
  • 1
    Oh. Understood. Thank you! – JRC Jul 14 '21 at 16:52