Thursday, 23 April 2015

Functions - the work horses of R

By way of a disclaimer, I’m not an R expert. I’m an experienced biochemist that believes R is a very valuable tool. As part of my learning curve, I’ve been trying to understand the fundamentals of R. Two core fundamentals are functions and objects. I’m going to write about functions here.


Functions do things in R. You often know something is a function by the presence of a set of round brackets. Looking at the script I wrote to analyse a protein assay, there are two functions with brackets in the first three lines of code.


The first function is denoted by
c(0.000, 0.016, 0.031, 0.063, 0.125, 0.250, 0.500, 1.000, 0.000, 0.016, 0.031, 0.063, 0.125, 0.250, 0.500, 1.000)
- this is the combine function. 

The code:


prot <- c(0.000, 0.016, 0.031, 0.063, 0.125, 0.250, 0.500, 1.000, 0.000, 0.016, 0.031, 0.063, 0.125, 0.250, 0.500, 1.000)


combines all the values into the object “prot”.


The second function is denoted by plot(abs~prot). This function draws a graph.


There is also another function <-. This is an assignment operator and is also a function.


Examples of other functions are also used in the Protein Assay script:
  • lm()- a function for fitting linear models.
  • abline()- a function for adding a straight line to a plot
  • text()- a function for adding text to a plot
  • round()- a function for rounding numbers


To make the function do what we want, we add arguments inside the brackets. Then close the bracket. The plot(abs~prot) function has the arguments abs and prot which provide the data for the x and y coordinates of the points on the plot.

To improve the plot, we add more arguments:

plot(abs~prot,
    xlab = "[Protein] (microg/ml)",
    ylab = "Absorbance (570nm)",
    main = "Protein Assay 20th April 2015")

In case you hadn’t worked it out, xlab gives a label for the x-axis, ylab gives the label for the y-axis and main gives the heading for the graph. The syntax is important and takes a bit of time to learn but R will give you an error message or produce a result that you don’t want if you get it incorrect. Then you can correct it.


Finding out more about functions

To find out more about a particular function, you can use the help in R by typing:

?plot
or
help(plot)

Either of these will give you an output in the help window in R-Studio. The help documentation can be complicated and can take a bit of time to work out. Be patient with yourself.

You can try the example function:
example(plot) - this will run examples if they have been coded as part of the documentation for the function.

You can search the internet and play with the code that you find. If you search
“plot r” in Google, you will find lots of useful resource. I like these two:

The official "Introduction to R" is available here.

No comments:

Post a Comment

Comments and suggestions are welcome.