Home > front end >  Provide multiple function arguments by one variable
Provide multiple function arguments by one variable

Time:12-28

When working with packages like openxlsx, I often find myself writing repetetive code such as defining the wb and sheet arguments with the same values.

To respect the DRY principle, I would like to define one variable that contains multiple arguments. Then, when I call a function, I should be able to provide said variable to define multiple arguments.

Example:

foo # should return `a=1,b=2,c=3`, but must be readable by bar()
  
bar <- function(a,b,c,d) {
  return(a b c d)
}

bar(foo, d=4) # should return 10

How should the foo() function be defined to achieve this?

CodePudding user response:

How should the foo() function be defined to achieve this?

You've got it slightly backwards. Rather than trying to wrangle the output of foo into something that bar can accept, write foo so that it takes input in a form that is convenient to you. That is, create a wrapper function that provides all the boilerplate arguments that bar requires, without you having to specify them manually.

Example:

bar <- function(a, b, c, d) {
  return(a b c d)
}

call_bar <- function(d=4) {
  bar(1, 2, 3, d)
}

call_bar(42)  # shorter than writing bar(1, 2, 3, 42)

CodePudding user response:

Let me give you an example! How to get two or more return values ​​from a function

Method 1: Set global variables, so that if you change global variables in formal parameters, it will also be effective in actual parameters. So you can change the value of multiple global variables in the formal parameter, then in the actual parameter is equivalent to returning multiple values.

Method 2: If you use the array name as a formal parameter, then you change the contents of the array, such as sorting, or perform addition and subtraction operations, and it is still valid when returning to the actual parameter. This will also return a set of values.

Method 3: Pointer variables can be used. This principle is the same as Method 2, because the array name itself is the address of the first element of the array. Not much to say.

Method 4: If you have learned C , you can quote parameters

You can try these four methods here, I just think the problem is a bit similar, so I provided it to you, I hope it will help you!

  •  Tags:  
  • r
  • Related