[Home]

Table of contents


Some features of R

For loops

R uses for-loops to loop over the elements of an array. Here is a quick example:
values = c(3, 5.6, -45)
for(x in values) {
   cat('x =', x, '\n')
}
This produces the output
x = 3 
x = 5.6 
x = -45
Notice the use of the keyword in.

Let me tell you some important points that make for-loops in R different from those in C.

You don't need loops much in R

If $x = (x_1,...,x_{100}),$ and you want to compute $y = (\sin x_1,...,\sin x_{100}),$ then you write a for-loop in C. However, in R just use a single line:
y = sin(x)
You should use such "implicit" loops whenever you can, as they are more efficient than the "explicit" for-loops.

Looping a fixed number of times

If you want to do something $n$ times, then in C you write:
for(i=0;i<n;i++) {
  printf("hello\n");
}
To achieve the same effect in R you need:
for(i in 1:n) {
  print('hello')
}
However, here i is going from 1 to $n$. If you want it to go from 0 to $n-1$, then use
for(i in 0:(n-1)) {
  print('hello')
}
Important: Don't use 0:n-1 instead of 0:(n-1). The former means "subtract 1 from 0:n".

Automatic printing is disabled inside a for-loop

If x is a variable in R, then you can print its value by simple typing its name by itself in a line (and hitting enter):
x = 1:10
x
Then the value of x gets printed automatically (without the need of any print or cat command:
 [1]  1  2  3  4  5  6  7  8  9 10
However, this does not work inside a for-loop:
for( x in 1:10) {
  x
}
This does not print anything on the screen. You need to use print or cat explicitly:
for( x in 1:10) {
  print(x)
}
to get output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

Functions

A function in R is like
f = function(x) {
  sin(x) - exp(x)
}
This is the function $f(x) = \sin x-e^x.$ You may think of this function is $f:{\mathbb R}\rightarrow{\mathbb R}$ or rather as $f:{\mathbb R}^n\rightarrow{\mathbb R}^n$ for every $n\in{\mathbb N}$ because R will automatically apply the function of each entry in an array. For example,
f(1:10)
produces:
[1]     -1.876811     -6.479759    -19.944417    -55.354953   -149.372083
[6]   -403.708209  -1095.976172  -2979.968629  -8102.671809 -22027.009816
You may use any number of arguments:
f = function(x,y,z) {
  x-y+z
}

g = function() {
   printf('hello!')
}
Here is a function from ${\mathbb R}$ to ${\mathbb R}^2:$
f = function(theta) {
  c(cos(theta), sin(theta))
}
Some functions in R have many arguments (even 100). It becomes very difficult to remember the position of all of them. R has two ways to deal with this problem: default values and labels.

If I write
f = function(x, y=30, z) {
  cat('x=',x,'y=',y,'z=',z)
}
then y has the default value 30. So you write
f(1,,3)
or
f(1,z=3)
to get the output
x= 1 y=30 z=3
For more details refer to my brief intro to R.

Comments

To post an anonymous comment, click on the "Name" field. This will bring up an option saying "I'd rather post as a guest."