Hello,
At the moment, I try to make the package with several function.
In my function I have 5 variables and I would like to know how I can put a default value of the variable when I omitted to put the variable when I call the function.
toto <- function(format, tab, seuil, taille, varf){ ...}
For example : when I call my function with only 4 variables
toto <- function(tab, seuil, taille, varf){ ...}
It miss the format variable.
Have you an idea of how I can put default value on format variable?
I want the default variable to be set to 1 i.e. format = 1
That example is demonstrating how to test for missing variables (ones not supplied in the function call) when your function has default values. The very first example in that section is a more basic example of just using default values:
f <- function(a = 1, b = 2) {
c(a, b)
}
f()
## [1] 1 2
With your example, you could have:
toto <- function(format = 1, tab, seuil, taille, varf){ ...}
The purpose of missing() is to let the function tell the difference between: i(b = 2) (the a value is being supplied by the default) and i(a = 3, b = 2) (the a value was supplied by the user, overriding the default), so that the function can do something differently in the two cases. This is pretty specialized — most functions have no need for missing(). It is not necessary if all you want to do is have some default values.
i <- function(a = 1, b) {
if(missing(a)) message("OK, I'll use the default a = 1")
a + b
}
i(b = 2)
#> OK, I'll use the default a = 1
#> [1] 3
i(a = 3, b = 2)
#> [1] 5
# Edited to add: Note what happens when we supply
# the same value as the default. This is why `missing()` is
# more powerful than just checking for a particular value
i(a = 1, b = 2)
#> [1] 3
I've made some function to create a specific package.
I use missing() in my function because the user can omit some variables and the function can run with default value.
Thanks!