Minh
Minh

Reputation: 2300

R: Using Arguments of One Function as Parameter for Another

I'm trying to create a custom function that has an arugment that requires the arguments of another function. For instance, something like this:

funct1 <- function(x,y,z){
   x + y + z
}

funct2 <- function(funct1, multiplier) {
  print("first arg is ": [funct1 x arg]
  print("second arg is ": [funct1 y arg]
  print("third arg is ": [funct1 z arg]
}

first <- funct1(1,2,3)
funct2(first1, 2) 
#first arg is 1
#second arg is 2
#third arg is 3

first <- funct1(3,4,5) #12
funct2(first1, 2) 
#first arg is 3
#second arg is 4
#third arg is 5

Upvotes: 0

Views: 51

Answers (2)

Dason
Dason

Reputation: 61903

If you want to be able to pass the function and arguments into the new function without having to define what those arguments are then you can use ...

f1 <- function(x, y, z){x + y + z}
f2 <- function(x, y){x * y}

doubler <- function(func, ...){
  func(...) * 2
}

f1(1, 2, 3)
# 6
doubler(f1, 1, 2, 3)
# 12
f2(3, 4)
# 12
doubler(f2, 3, 4)
# 24

Upvotes: 2

Badger
Badger

Reputation: 1053

You simply need to have the same variable in each. What is the end game for this though?

funct1 <- function(x,y,z){
   x + y + z
}

funct2 <- function(x,y,z) {
  funct1(x,y,z) * 2
}

funct2(3,4,5)

> 24

Upvotes: 1

Related Questions