Home > Back-end >  Using do.call() to pass arguments from 2 different lists into a function with 2 parameters in R
Using do.call() to pass arguments from 2 different lists into a function with 2 parameters in R

Time:09-27

I have been struggling to implement do.call(). I have a function that I have to run many times to generate a series of different plots. Instead of inputting each argument, I want each pair of arguments to be accessed from a table. This seems like it should be possible with do.call() but I can't seem to figure it out.

Here is a basic example I made to try to troubleshoot how to accomplish this.

fun <- function(x, y) {
  z = x   y
  assign(gsub(" ","_",paste("sum of", x, "and", y)), z, env=.GlobalEnv) 
}

list_x = as.list(c(1, 2, 3))
list_y = as.list(c(4, 3, 2))

do.call(fun, c(list_x, list_y))

sum_of_1_and_4
sum_of_2_and_3
sum_of_3_and_2

However, I get the following error:

Error in (function (x, y)  : unused arguments (3, 4, 3, 2)

CodePudding user response:

I think mapply() might be a better fit in this situation:

fun <- function(x, y) {
  z = x   y
  assign(gsub(" ","_",paste("sum of", x, "and", y)), z, env=.GlobalEnv) 
}
list_x = as.list(1, 2, 3)
list_y = as.list(4, 3, 2)

mapply(fun, list_x, list_y)

Yielding the following output:

sum_of_1_and_4
[1] 5
sum_of_2_and_3
[1] 5
sum_of_3_and_2
[1] 5
  • Related