Reputation: 119
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]
Upvotes: 1
Views: 1270
Reputation: 389235
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
Upvotes: 0
Reputation: 77116
try this,
fruitsandvegetables <- function(tomatoes, ...){
fruits(...) + tomatoes
}
Note: problems may arise if a tomato turns out to be a fruit
Upvotes: 4