1

Consider the first function:

fruits <- function(apples, oranges){
   apples + oranges
}

#example#
> fruits(2,3) 
[1] 5

The second function uses the first function fruits:

fruitsandvegetables <- function(tomatoes){
   fruits(apples, oranges) + tomatoes
}

Now consider the following errors:

> fruitsandvegetables(3)
  Error in fruits(apples, oranges) : object 'apples' not found
> fruitsandvegetables(3, apples = 2, oranges = 3)
  Error in fruitsandvegetables(3, apples = 2, oranges = 3) : 
  unused arguments (apples = 2, oranges = 3)
> fruitsandvegetables(tomatoes = 3, apples = 2, oranges = 3)
  Error in fruitsandvegetables(tomatoes = 3, apples = 2, oranges = 3) : 
  unused arguments (apples = 2, oranges = 3)

I understand these errors, but I was wondering if there is a simple way to get around this. For more complex function with many arguments, rewriting the functions can be very tedious.

In otherwords I would like the function to behave this way:

fruitsandvegetables(3, apples = 2, oranges =3)
[8]
1
  • 2
    fruitsandvegetables function should be fruitsandvegetables <- function(tomatoes, apples, oranges){ fruits(apples, oranges) + tomatoes } Commented Oct 25, 2016 at 6:11

2 Answers 2

4

try this,

fruitsandvegetables <- function(tomatoes, ...){
  fruits(...) + tomatoes
}

Note: problems may arise if a tomato turns out to be a fruit

Sign up to request clarification or add additional context in comments.

1 Comment

I think the use of ... is far more elegant and flexible than using missing or making sure all nested functions share the same argument names as their higher/lower level functions
0

There is no way fruitsandvegetables function comes to know what is apples and oranges.

You may include these two parameters as argument to the function like ,

fruitsandvegetables <- function(tomatoes, apples, oranges) {
     fruits(apples, oranges) + tomatoes 
}

fruitsandvegetables(3, apples = 2,oranges = 3)
#[1] 8

Moreover,

fruitsandvegetables(3,2,3)
#[1] 8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.