0

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
5
  • are you planning on changing variable values in funct1() or not? That fundamentally changes the answer. Commented Oct 8, 2015 at 19:19
  • yes, the values of funct1 as I plan on assigning it to different objects. What I'm trying to do is make funct2 dynamically depending on what is passed with funct1. Hope this helps! Commented Oct 8, 2015 at 19:20
  • You really should have made that clear and then @Honey wouldn't have been led down the wrong path. Commented Oct 8, 2015 at 19:21
  • Apologies, I'm editing my question now after reading his comment. Commented Oct 8, 2015 at 19:22
  • So you either need to think more about what you're asking or give us more detail. Presently funct1 takes three inputs and returns 1, yet you think that you're going to use them from that function. You're not. Commented Oct 8, 2015 at 19:32

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Right, I guess I should specify that I'm trying to avoid having to put in the same arguments. I can just assign funct1 to an object and then pass that along into funct2
funct2 <- function() { funct1(3,4,5) * 2 } Will work, but I'm still not really sure why you would do this? You could just go funct1(3,4,5) *2 you know?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.