Much like my other basic post on functions… R has it’s own use of functions.

In R, you assign a function class to a object (remember in R class and object mean something different then in OO languages.)  A class is like a type (int, character, etc.)  and object is like the symbol.

f <- function(argument){
   some code
}

In the above example, the symbol (object) f, is set to the class type function.

Example:

f <- function(a, b){
   a^b
}

so f(5,10) would run the calculation of 5^10

Believe it or not, … is actually used.  It represents a placeholder for other parameters.  You may want to add an argument to a function, but not want to list out all the arguments, so you use … to refer to the pre existing arguments.

Other Function Examples

If we wanted to have a function that took two values. The first being a number or range, and the second being a threshold, we could do:

myFunc <- function(x,n=10){
   check <- x > n
   x[check]
}

in the above example n has a default value of 10. So if a person doesn’t pass in a value for  n, n is defaulted to 10.

 

Leave a Reply

Your email address will not be published. Required fields are marked *