Sunday 19 July 2015

R: Passing default values to function parameters

In R, you can pass default values to function parameters. If caller don’t pass any value to the parameters, then R use the default values.

How to set default values
Assign a value to the parameter at the time of function definition.
add <- function(x=10, y=5){
  return(x+y)
}

sub <- function(x=10, y=5){
  return(x-y)
}

mul <- function(x=10, y=5){
  return(x*y)
}

div <- function(x=10, y=5){
  return(x/y)
}

addition <- add()
subtraction <- sub(,20)
multiplication <- mul(20,)
division <- div()

sprintf("Addition : %d", addition)
sprintf("subtraction : %d",subtraction)
sprintf("multiplication : %d",multiplication)
sprintf("division : %d",division)


$ Rscript FunctionEx.R 
[1] "Addition : 15"
[1] "subtraction : -10"
[1] "multiplication : 100"
[1] "division : 2"

add <- function(x=10, y=5)
Above statement assign x to 10, y to 5 if caller don’t provide values to parameters.

add() becomes add(10, 5)
sub(,20) becomes sub(10,20)
mul(20,) becomes mul(20,5)

div() becomes div(10,5)



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment