r-advanced

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

UPPSALA UNIVERSITY Mathematical Statistics

Department of Mathematics Multivariate Methods


Måns Thulin – thulin@math.uu.se Spring 2011

MORE ADVANCED USE OF R


Eventually you might want to use R for somewhat more advanced programming. This
text aims to give a short introduction to some useful parts of the R language that you
might not encounter in the computer exercises but that nevertheless are good to know
about. It is assumed that you already are familiar with programming; in particular that
you have seen if conditions and loops before.

1 A second look at vectors


We’ve seen that vectors can be created using c or seq. Another alternative is rep which
gives us vectors with certain patterns.
x<-rep(1,10) # Gives the vector (1,1,1,1,1,1,1,1,1,1)
y<-rep(c(1,2,3),2) # Gives the vector (1,2,3,1,2,3)
z<-rep(c(1,2),c(2,3)) # Gives the vector (1,1,2,2,2)
Specific elements of vectors can be accessed using clever expressions for indexing. Here
are some examples:
x[n] # The n:th element of x
x[-n] # All elements but the n:th
x[a:b] # All elements between the a:th and the b:th
x[c(1,3,7)} # The first, the third and the seventh element
x[x>2] # All elements that are greater than 2

2 Programming
if statements and booleans
Boolean expressions can be written in R in much the same way as in many other
programming languages. Here are some examples:
a<-1; b<-2; c<-3
a==a # Checks if a equals a
a==b # Checks if a equals b
a!=b # Checks if a does not equal b
!(a==b) # Checks if a does not equal b
a<b # Checks if a is less than b
a<=b # Checks if a is less than or equal to b
a<b && a<c # Checks if a is less than b _and_ if a is less than c
a<b || c<a # Checks if a is less than b and/or c is less than a

1
Each expression returns either TRUE or FALSE. Boolean variables are variables that take
either of these values.

Boolean expressions are useful when using if statements. These can be used to make
sure that certain parts of the code only run under special conditions. Here is an example
of what an if statement can look like in R:

iIsLarge<-FALSE; i<-20
if(i>=10) { iIsLarge<-TRUE } # Checks if i is large
iIsLarge # The boolean variable that tells us if i is large

if can also be combined with else to control what happens if the boolean expression
is false:

i<-runif(1,0,20) # A random number between 0 and 20


if(i>=10) { iIsLarge<-TRUE } else { iIsLarge<-FALSE }
iIsLarge

Loops
Booleans can also be used in the while loop as follows:

count=0; ourRandomNumber<-runif(1,0,40)
while(ourRandomNumber>10)
{
newRandomNumber<-runif(1,0,40)
ourRandomNumber<-newRandomNumber
count<-count+1 # Counts the number of iterations of the loop
}
count

An alternative is the for loop:

x<-rep(NA,10)
for(i in 1:10)
{
x[i]<-i^2
}
x

Althought it is considered to be bad practice, the break command can be used to stop
loops:

x<-rep(NA,10)
for(i in 1:10)
{
x[i]<-i^2
if(i^2>10) { break }
}
x

2
Functions
Creating new functions in R is quite easy. Consider the following example:
powern<-function(x,n=2)
{
z<-x^n
return(z)
}
This creates a function powern which takes two arguments, a vector (or scalar) x and
a vector (or scalar) n. If the argument n is not given in the call then the default value
n=2 is used instead. The function returns x∧ n.
The function can now be called just as any other function:
powern(2)
powern(3,1/2)
powern(6,-1)
x<-c(1,2,3); powern(x,x)
However, if you want to use the function again, it must be defined once more each
time that you start R (unless you choose to save the workspace image at the end of the
previous session).

3 Files and scripts


Saving text files
In the introduction to R we saw that we could import data from text files into data
frames using the read.table command. In the same manner we can save data as text
files using write.table. Here is an example that saves the mtcars data frame in the
file mtcars.txt:
data(mtcars)
write.table(mtcars,file="mtcars.txt")
The data can now be imported into R (by you or someone else) by the read.table
command.

Saving graphics
In the Windows version of R figures can be saved by right-clicking on them. An alter-
native is to save the figure by using the following code:
pdf("fig1.pdf", width=8, height=8, title="My pdf")
plot(x,y,xlab="x-axis",ylab="y-axis",main="This is my plot")
dev.off()
This saves the plot in the file fig.pdf. It is possible to save the figure in other file
formats by exchanging
pdf("fig1.pdf", ...

3
in the above with any of the following

postscript("fig1.ps", ...
postscript("fig1.eps", ...
png(file="fig1.png", ...
jpeg(file="fig1.jpg", ...
bitmap(file="fig1.bmp", ...

Executing scripts
If we’ve saved an R-script in the file script.R and want to execute it we can write

source("script.R", echo=TRUE)

If echo=TRUE is in the call the commands in the script are printed on the screen and if
echo=FALSE then the script is executed without printing the commands.

You might also like