How to use functions in RLearn to write them with control structures

There are a lot of predefined functions in R commander going from basic mathematical functions to complex statistical functions. Calling a function in R is easy, just write the function name and fill in the correct parameters. Remember, the help file helps a lot with setting the correct parameters. It is also possible to write your own functions in combination with the R control structures. How to call and write functions in R and how to use control structures will be explained in this tutorial.

Calling functions in R

Calling functions means using predefined functions that already exist in R commander. Example:

  • log(100)

This command will call for the logarithmic function in R. Use the help function if you don't know what parameters should be used in this function.

The help file says: log(x, base = exp(1)). These are the parameters that should be used. Note that parameters may switch order, if you name them. Example:

  • log(base=10, x=120)

Writing functions in R

It is possible in R to write your own functions. In order to write functions, you should have the know how about assigning variables in R. Example:

  • a = 15 or a < - 15   # gives the variable a the value 15.
  • newFunction = function(parameter one, parameter two, ... )   # Makes the function newFuntion
  •    {
  •          Statements
  •          return(value)
  •    }

Control structures in R

Using control structures should not be a problem if you know how to program. This control structures may be used to write functions in R. :

  • if (condition) expression
  • if (condition) expression else expression
  • for (var in sequence) expression
  • while (condition) expression
  • repeat expression

Expressions are statements, for example an if structure. The condition always returns true or false (boolean value). Following boolean operators may be used in R:

  • ! x # Not X
  • x & y # Logic AND
  • x && y # Logic AND
  • x | y # Logic OR
  • x || y # Logic OR
  • xor(x, y) # X or Y, not both