Programming

Script

R-scripts are documents containing a series of commands. They can be ordered to perform a specific task or they can just be a series a commands executing specific sub-tasks.
 
To create a script called myscript, on your R-interface,
 

1. Go to File -> New document.
2. Write the commands for the previous function stat in the new.
3. Save the script in your working directory as myscript.R. It is an R-file.

 
To run the script, 
 

1. File -> Source file -> choose myscript.R in the working directory.         # The "source" command compiles your code and checks for errors. If there is no errors, no message is displayed. An error message will be displayed otherwise.
2. Call your script with the command myscript() in the command window.        # The empty parenthesis are used when there is no argument called in your script!

 

Functions

You can create your own functions with R, using scripts. To create a function called myfunction with arguments arg1, arg2, ...., argn,
 

1. use the syntax myfunction-<function(arg1, arg2,....., argn) {  body of the function } and save it as myfunction.R to your working directory. Note that function is specific term used by R and cannot be changed! 2. call the function using the command myfunction(arg1, arg2,....., argn

 
Example: 

parabola<function(x){  y=x^2, plot(x,y,type="l",col="red") }         # This function plots the curve of the function y=x2.
parabola(seq(-10,10,0.1))                                            # we apply the function parabola over the interval [-10,10] using equally spaced points by 0.1.

 
Logical Operators
 Operator  Description
 &  And 
 |  Or 
 !  Not

Comparison Operators
 Operator  Description
 ==  Equal
 !=  Nor equal
 >  Greater than
 >=  Greater than or equal
 <  Less than
 <=  Less than or equal

Loops
 Type of loop  Description
 if   if (condition1=TRUE) {statements 1} else {statements 2}
 Ifelse    ifelse(test, true-value, false-value)  
 For   for (variable in sequence) {statements} 
 While    while (condition) { statements} 
Examples:
 

> x = 1 : 10
> if (mean(x)<5.5){x=x+1}else{print(x+1)}      # Print the values of x+1 if the mean of x is less than 5.5.
  [1]  2  3  4  5  6  7  8  9 10 11

 
>ifelse(x<5|x>8,x,40)                         # what this does is to replace values between 5 and 8 with 40.

  [1]  1  2  3  4 40 40 40 40  9 10