Tuesday 21 July 2015

R: Function argument matching

n R, Function arguments can be matched by name (or) position.

Match by Position

FunctionEx.R
add <- function(x, y){
  print(x)
  print(y)
  return(x+y)
}

addition <- add(10, 20)
sprintf("Addition : %d", addition)

addition <- add(10, 20)
Above statement assign 10 to x and 20 to y.

$ Rscript FunctionEx.R 
[1] 10
[1] 20
[1] "Addition : 30"


Match by name
R supports,  assigning value to parameters by name.

FunctionEx.R

add <- function(x, y){
  print(x)
  print(y)
  return(x+y)
}

addition <- add(y=10, x=20)
sprintf("Addition : %d", addition)

$ Rscript FunctionEx.R 
[1] 20
[1] 10
[1] "Addition : 30"


addition <- add(y=10, x=20)
Above statement assigns 10 to y and 20 to x.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment