Showing posts with label fundamentals. Show all posts
Showing posts with label fundamentals. Show all posts

Monday, 7 March 2016

Illustrating some R Fundamentals for VizBi 2016

I have surveyed the participants for my R tutorial at VizBi2016. The range of experience is a bit of a challenge. Some participants that have used R once or twice and others with plenty of experience. It's going to be a bit difficult to make the morning useful for everybody but I will try....

For the beginners, I'm going to start with this script which is designed to illustrate three of the fundamentals of R:

  • functions
  • objects
  • packages

It's an expansion of the script to draw a graph of a protein assay with ggplot:


Here is the script:
# First script for VizBi2016
# written to illustrate the Fundamentals of R

## first 'Fundamental' is ** functions **
# functions do things!
# you know it's a function because it contains brackets

# c() is a function - sometimes called combine

## second 'Fundamental' is ** objects **
# objects contain data
# we make them with functions

# example:
# using the c() function to create the object prot
# Protein Concentrations
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) 

# a function has arguments - always inside the brackets

# Absorbance from my protein assay
abs <- c(0.329, 0.352, 0.349, 0.379, 0.417, 0.491, 0.668, 0.956, 
         0.327, 0.341, 0.355, 0.383, 0.417, 0.446, 0.655, 0.905)

# these objects are called 'vectors' - key term

## now we are going ot play with some of these objects to 

#Calculate the line using the linear model function lm()
line <- lm(abs~prot)

# creates another kind of object - a list
# multiple parts with different type of data in each part

# too look at the object type line
line
summary(line)

# access particular parts of the object line
# using the $ dollar sign
# Equation of a line y = mx + c
# In our case abs = slope * prot + intercept
# ukn.prot = (abs - intercept)/slope
int <- summary(line)$coefficients[1]
slope <- summary(line)$coefficients[2]

# now calculate some unknown protein concs from absorbances
# put the unknowns into a vector
abs.ukns <- c(0.554, 0.568, 0.705)

# rearrange the equation of the line to ukn.prot = (abs - intercept)/slope
prot.ukns <- (abs.ukns - int)/slope

# CONCEPT ALERT - functions work on a vector of numbers


## graphing

# quick graph using base R
plot(prot, abs)
abline(line)

## BUT there is a better way!!

## third 'Fundamental' is ** packages **
# these are collections of functions that have been written by others
# these can be installed 
# install.packages("ggplot2")
# and then activated
library(ggplot2)

# Convert from one type of object to another
# another kind of object is a data.frame
# a bit like an Excel spreadsheet
# often when we import data we get a data frame
data <- as.data.frame(prot)
data$abs <- abs


# make a simple graph with ggplot
# step one - add the data and then the 'aesthetics' 
# key asthetics in this case x and y
p <- ggplot(data=data,          # specify the data frame with data
            aes(x=prot, y=abs)) # specify x and y for the graph

# creates a list and a blank plot

# add a type of graph 
p <- p + geom_point()

# show the graph
p

# add a line
p + stat_smooth(method = "lm")

# more detailed plot: 
p <- ggplot(data=data,          # specify the data frame with data
            aes(x=prot, y=abs)) +   # specify x and y for the graph
  geom_point() +          # make a scatter plot
  stat_smooth(method = "lm") +  # add a linear model line
  xlab("[Protein] (microg/ml)") +   # label x-axis
  ylab("Absorbance (570nm)") +    # label y-axis
  ggtitle("Protein Assay") +  # add a title
  theme_bw() +      # a simple theme
  expand_limits(y=c(0,1)) +    # customise the y-axis
  annotate(geom="text", x=0.85, y= 0.6, label="Abs         Prot",  color="red")

# put the answers on the graph
for (i in 1:length(abs.ukns)){
  p <- p + annotate(geom="text", x = 0.8, y = (0.6 - i/20), label=abs.ukns[i])
  p <- p + annotate(geom="text", x = 0.92, y = (0.6 - i/20), label=round(prot.ukns[i], 3))
}

p # show us the graph...

## To Learn from this script:
# run this script line by line yourself and see what happens.
# watch what happens

# make the plot object again and try some things...
p <- ggplot(data=data,          # specify the data frame with data
            aes(x=prot, y=abs)) # specify x and y for the graph

# try to change the colour of the points
p + geom_point(colour = "blue")

# try to change the size of the points
p + geom_point(size = 5, colour = "red")

# look at the documentation for geom_point
# http://docs.ggplot2.org/current/geom_point.html
# try some of the functions and see if you can make sense of them






Wednesday, 27 May 2015

Exploring Data Structures...

I am preparing my slide for the R for Biochemists Training Day.
One of the key things to explain is the importance of objects in R.
Data is located in objects and there are a variety of data structures and data types.

I have written an R script to try to explore objects, particularly data structures.

I use three of the types of data structures regularly:

I create these objects using the assignment operator "<-" or functions like lm().

I  apply functions to these objects. For example plot()

I extract data from these functions using square brackets [] or $

Scripts and R Markdown files are available on Github

I have learned a lot from these sources:



# START of SCRIPT
# Exploring Data Structures

## objects are made up of various types. 
## I want to discuss objects that contain data

## Data goes into objects
### Use the assignment function "<-"
### Protein Concentrations
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) 

### Absorbance from my protein assay
abs <- c(0.329, 0.352, 0.349, 0.379, 0.417, 0.491, 0.668, 0.956, 
         0.327, 0.341, 0.355, 0.383, 0.417, 0.446, 0.655, 0.905)
### these appear in the R-Studio environment as Values

## These objects are vectors - all the data elements must be the same type
### A vector is the simplist type of object
### can be numeric, character, logical, factors
class(prot)  #### numeric

### Some other types of vectors
protein <- "albumin"
class(protein) #### character

truth <- c(TRUE, FALSE, TRUE, TRUE)
class(truth) #### logical

### you can identify things inside the objects
prot[2]

### and parts of objects
prot[1:8]

### functions can be applied to whole objects (particularly arrays)
### the plot function puts the first element of each object against each other
plot(abs~prot)


# More Complicated structures
## <b>lists</b> are another type of object
## the lm() function makes an object called line which is a list. 
## lists contain a mixture of data types. 
line <- lm(abs~prot)
### the R-Studio environment says a "List of 12"

## there are various ways of getting information from this object 
## type the name of the object
line

## use the summary() function
summary(line)

## use the $ 
summary(line)$r.squared

### we used this to extract the r2
### we created the object r2 using the function summary()
r2 <- summary(line)$r.squared
### and the function round() - gives us three decimal points
r2 <- round(summary(line)$r.squared, 3)
r2
class(r2)
### from the list we have extracted a number. 

# <b>matrices</b> are two dimensional structures 
##  the data types are all the same

# <b>data frames</b> are two dimensional structures
##  contains different types of data

# often when we import data, it gets imported as a data frame.
## here is an example:
data <- read.csv("http://science2therapy.com/data/wellsDataSimp.csv")

## the R-Studio environment puts it in "data" and gives us some info

## Have a quick look at it
View(data)  # works in R-Studio
str(data)

## we have names of columns and we have the class of the data within the column
## note: Factors, num, int
data$Virus

# Simple plot from this data frame
plot(data[5:7])

## Another plot from this data frame
plot(data$P.Erk, data$S.phase.cnt)

## we can manipulate objects including data frames 
## which is the subject of the next tutorial.



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.