how to define a function in R code example

Example 1: fuction in r

# Create a function to print squares of numbers in sequence.
new.function <- function(a) {
   for(i in 1:a) {
      b <- i^2
      print(b)
   }
}

# Call the function new.function supplying 6 as an argument.
new.function(6)

Example 2: calculated defualt values in R function parameters

fun <- function(x,levels=levels(x)){
    blah blah blah
}

Example 3: calculated defualt values in R function parameters

fun <- function(x,y=getOption('fun.y','initialDefault')){# or getOption('pkg.fun.y',defaultValue)
    blah blah blah
}

Tags:

R Example