R is a programming language for statistical computing, and data wrangling. It is open-source, widely used in data science, has a wide range of functions and algorithms for graphing and data analyses.

1 Assignment operator

Variables are assigned usually using the <- operator. The = operator also works in a similar way for most part.

x <- 4
x = 4
x
## [1] 4

2 Arithmetic operators

The commonly used arithmetic operators are shown below returning a number.

x <- 4
y <- 2

# add
x + y

# subtract
x - y

# multiply
x * y

# divide
x / y

# modulus
x %% y

# power
x ^ y
## [1] 6
## [1] 2
## [1] 8
## [1] 2
## [1] 0
## [1] 16

3 Logical operators

Logical operators return a logical TRUE or FALSE.

# equal to?
x == y

# not equal to?
x != y

# greater than?
x > y

# less than?
x < y

# greater than or equal to?
x >= y

# less than or equal to?
x <= y
## [1] FALSE
## [1] TRUE
## [1] TRUE
## [1] FALSE
## [1] TRUE
## [1] FALSE

4 Data types

class(1)
class("hello")
class(T)
## [1] "numeric"
## [1] "character"
## [1] "logical"
x <- c(2,3,4,5,6)
y <- c("a","c","d","e")
z <- factor(c("a","c","d","e"))
class(z)
## [1] "factor"
x <- matrix(c(2,3,4,5,6,7),nrow=3,ncol=2)
class(x)
str(x)
## [1] "matrix" "array" 
##  num [1:3, 1:2] 2 3 4 5 6 7
dfr <- data.frame(x = 1:3, y = c("a", "b", "c"))
print(dfr)
##   x y
## 1 1 a
## 2 2 b
## 3 3 c
class(dfr)
## [1] "data.frame"
str(dfr)
## 'data.frame':    3 obs. of  2 variables:
##  $ x: int  1 2 3
##  $ y: chr  "a" "b" "c"

5 Accessors

Vectors positions can be accessed using []. R follows 1-based indexing.

x <- c(2,3,4,5,6)
x
x[2]
## [1] 2 3 4 5 6
## [1] 3

Dataframe or matrix positions can be accessed using [] specifying row and column like [row,column].

dfr <- data.frame(x = 1:3, y = c("a", "b", "c"))
dfr
dfr[1,]
dfr[,1]
dfr[2,2]
##   x y
## 1 1 a
## 2 2 b
## 3 3 c
##   x y
## 1 1 a
## [1] 1 2 3
## [1] "b"

6 Functions

# generate 10 random numbers between 1 and 200
x <- sample(x=1:200,10)
x

# length
length(x)

# sum
sum(x)

# mean
mean(x)

# median
median(x)

# min
min(x)

# log
log(x)

# exponent
exp(x)

# square-root
sqrt(x)

# round
round(x)

# sort
sort(x)
##  [1] 196 185  42 186 112  83  50 119 188 156
## [1] 10
## [1] 1317
## [1] 131.7
## [1] 137.5
## [1] 42
##  [1] 5.278115 5.220356 3.737670 5.225747 4.718499 4.418841 3.912023 4.779123
##  [9] 5.236442 5.049856
##  [1] 1.323483e+85 2.210442e+80 1.739275e+18 6.008605e+80 4.375039e+48
##  [6] 1.112864e+36 5.184706e+21 4.797813e+51 4.439792e+81 5.622626e+67
##  [1] 14.000000 13.601471  6.480741 13.638182 10.583005  9.110434  7.071068
##  [8] 10.908712 13.711309 12.489996
##  [1] 196 185  42 186 112  83  50 119 188 156
##  [1]  42  50  83 112 119 156 185 186 188 196

Some useful string functions.

a <- "sunny"
b <- "day"

# join
paste(a, b)

# find a pattern
grep("sun", a)

# number of characters
nchar("sunny")

# to uppercase
toupper("sunny")

# to lowercase
tolower("SUNNY")

# replace pattern
sub("sun", "fun", "sunny")

# substring
substr("sunny", start=1, stop=3)
## [1] "sunny day"
## [1] 1
## [1] 5
## [1] "SUNNY"
## [1] "sunny"
## [1] "funny"
## [1] "sun"

Some general functions

print("hello")
print("world")
cat("hello")
cat(" world")
cat("\nhello\nworld")
## [1] "hello"
## [1] "world"
## hello world
## hello
## world

7 Merging

Two strings can be joined together using paste().

a <- "sunny"
b <- "day"

paste(a, b)
paste(a, b, sep="-")
## [1] "sunny day"
## [1] "sunny-day"

The function c() is used to concatenate objects.

a <- "sunny"
b <- "day"

c(a,b)
## [1] "sunny" "day"

The function cbind() is used to join two dataframes column-wise.

dfr1 <- data.frame(x = 1:3, y = c("a", "b", "c"))
dfr2 <- data.frame(p = 4:6, q = c("d", "e", "f"))
dfr1
dfr2

cbind(dfr1,dfr2)
##   x y
## 1 1 a
## 2 2 b
## 3 3 c
##   p q
## 1 4 d
## 2 5 e
## 3 6 f
##   x y p q
## 1 1 a 4 d
## 2 2 b 5 e
## 3 3 c 6 f

Similarily, rbind() is used to join two dataframes row-wise.

dfr1 <- data.frame(x = 1:3, y = c("a", "b", "c"))
dfr2 <- data.frame(x = 4:6, y = c("d", "e", "f"))
dfr1
dfr2

rbind(dfr1,dfr2)
##   x y
## 1 1 a
## 2 2 b
## 3 3 c
##   x y
## 1 4 d
## 2 5 e
## 3 6 f
##   x y
## 1 1 a
## 2 2 b
## 3 3 c
## 4 4 d
## 5 5 e
## 6 6 f

Two dataframes can be merged based on a shared column using the merge() function.

dfr1 <- data.frame(x = 1:4, p = c("a", "b", "c","d"))
dfr2 <- data.frame(x = 3:6, q = c("l", "m", "n","o"))
dfr1
dfr2

merge(dfr1,dfr2,by="x")
merge(dfr1,dfr2,by="x",all.x=T)
merge(dfr1,dfr2,by="x",all.y=T)
merge(dfr1,dfr2,by="x",all=T)
##   x p
## 1 1 a
## 2 2 b
## 3 3 c
## 4 4 d
##   x q
## 1 3 l
## 2 4 m
## 3 5 n
## 4 6 o
##   x p q
## 1 3 c l
## 2 4 d m
##   x p    q
## 1 1 a <NA>
## 2 2 b <NA>
## 3 3 c    l
## 4 4 d    m
##   x    p q
## 1 3    c l
## 2 4    d m
## 3 5 <NA> n
## 4 6 <NA> o
##   x    p    q
## 1 1    a <NA>
## 2 2    b <NA>
## 3 3    c    l
## 4 4    d    m
## 5 5 <NA>    n
## 6 6 <NA>    o

8 Packages

R packages extend the functionality of base R. R packages are stored in repositories of which the most commonly used is called CRAN (The Comprehensive R Archive Network).

Packages are installed using the function install.packages(). Let’s install the graphics and plotting package ggplot2 which will be useful in later sections.

install.packages("ggplot2",dependencies=TRUE)

Packages on BioConductor can be installed as follows:

source("https://bioconductor.org/biocLite.R")
biocLite("biomaRt")

Packages on GitHub can be installed using the function install_github() from package devtools.

Packages can also be installed from a local zipped file by providing a local path ans setting type="source".

install.packages("./dir/package.zip",type="source")

Inside RStudio, installing packages is much easier. Go to the Packages tab and click Install. In the window that opens up, you can find your package by typing into the Packages field and clicking Install. Bioconductor packages can be added to this list by setting it using setRepositories().

9 Graphics

9.1 Base

R is an excellent tool for creating graphs and plots. The graphic capabilities and functions provided by the base R installation is called the base R graphics. Numerous packages exist to extend the functionality of base graphics.

We can try out plotting a few of the common plot types. Let’s start with a scatterplot. First we create a data.frame as this is the most commonly used data object.

dfr <- data.frame(a=sample(1:100,10),b=sample(1:100,10))

Now we have a dataframe with two continuous variables that can be plotted against each other.

plot(dfr$a,dfr$b)

This is probably the simplest and most basic plots. We can modify the x and y axis labels.

plot(dfr$a,dfr$b,xlab="Variable a",ylab="Variable b")

We can change the point to a line.

plot(dfr$a,dfr$b,xlab="Variable a",ylab="Variable b",type="b")

Let’s add a categorical column to our dataframe.

dfr$cat <- rep(c("C1","C2"),each=5)

And then colour the points by category.

# subset data
dfr_c1 <- subset(dfr,dfr$cat == "C1")
dfr_c2 <- subset(dfr,dfr$cat == "C2")

plot(dfr_c1$a,dfr_c1$b,xlab="Variable a",ylab="Variable b",col="red",pch=1)
points(dfr_c2$a,dfr_c2$b,col="blue",pch=2)

legend(x="topright",legend=c("C1","C2"),
       col=c("red","blue"),pch=c(1,2))

Let’s create a barplot.

ldr <- data.frame(a=letters[1:10],b=sample(1:50,10))
barplot(ldr$b,names.arg=ldr$a)

9.2 Grid

Grid graphics have a completely different underlying framework compared to base graphics. Generally, base graphics and grid graphics cannot be plotted together. The most popular grid-graphics based plotting library is ggplot2.

Let’s create the same plot are before using ggplot2. Make sure you have the package installed.

library(ggplot2)

ggplot(dfr,aes(x=a,y=b,colour=cat))+
  geom_point()+
  labs(x="Variable a",y="Variable b")

It is generally easier and more consistent to create plots using the ggplot2 package compared to the base graphics.

Let’s create a barplot as well.

ggplot(ldr,aes(x=a,y=b))+
  geom_bar(stat="identity")

10 Input/Output

Input and output of data and images is an important aspect with data analysis.

10.1 Text

Data can come in a variety of formats which needs to be read into R and converted to an R data type.

Text files are the most commonly used input. Text files can be read in using the function read.table. We have a sample file to use: iris.txt.

dfr <- read.table("iris.txt",header=TRUE,stringsAsFactors=F)

This reads in a tab-delimited text file with a header. The argument sep='\t' is set by default to specify that the delimiter is a tab. stringsAsFactors=F setting ensures that character columns are not automatically converted to factors.

It’s always a good idea to check the data after import.

head(dfr)
str(dfr)

Check ?read.table for other wrapper functions to read in text files.

Let’s filter this data.frame and create a new dataset.

dfr1 <- dfr[dfr$Species == "setosa",]

And we can write this as a text file.

write.table(dfr1,"iris-setosa.txt",sep="\t",row.names=F,quote=F)

sep="\t" sets the delimiter to tab. row.names=F denotes that rownames should not be written. quote=F specifies that doubles must not be placed around strings.

10.2 Images

Let’s take a look at saving plots.

10.3 Base graphics

The general idea for saving plots is open a graphics device, create the plot and then close the device. We will use png here. Check out ?png for the arguments and other devices.

dfr <- data.frame(a=sample(1:100,10),b=sample(1:100,10))

png(filename="plot-base.png")
plot(dfr$a,dfr$b)
dev.off()

10.4 ggplot2

The same idea can be applied to ggplot2, but in a slightly different way. First save the file to a variable, and then export the plot.

p <- ggplot(dfr,aes(a,b)) + geom_point()

png(filename="plot-ggplot-1.png")
print(p)
dev.off()

ggplot2 also has another easier helper function to export images.

ggsave(filename="plot-ggplot-2.png",plot=p)

11 Getting help

  • Use ?function to get function documentation
  • Use ??bla to search for a function
  • Use args(function) to get the arguments to a function
  • Go to the package CRAN page/webpage for vignettes
  • R Cookbook: General purpose reference.
  • Quick R: General purpose reference.
  • Stackoverflow: Online community to find solutions to your problems.

12 Session info

## R version 4.0.3 (2020-10-10)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 18.04.5 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/openblas/libblas.so.3
## LAPACK: /usr/lib/x86_64-linux-gnu/libopenblasp-r0.2.20.so
## 
## locale:
##  [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8       
##  [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8   
##  [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C          
## [10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C   
## 
## attached base packages:
## [1] parallel  stats4    stats     graphics  grDevices utils     datasets 
## [8] methods   base     
## 
## other attached packages:
##  [1] stringr_1.4.0               scales_1.1.1               
##  [3] fgsea_1.16.0                enrichR_2.1                
##  [5] rafalib_1.0.0               pvclust_2.2-0              
##  [7] pheatmap_1.0.12             biomaRt_2.46.0             
##  [9] edgeR_3.32.0                limma_3.46.0               
## [11] DESeq2_1.30.0               SummarizedExperiment_1.20.0
## [13] Biobase_2.50.0              MatrixGenerics_1.2.0       
## [15] matrixStats_0.57.0          GenomicRanges_1.42.0       
## [17] GenomeInfoDb_1.26.1         IRanges_2.24.0             
## [19] S4Vectors_0.28.0            BiocGenerics_0.36.0        
## [21] ggplot2_3.3.2               formattable_0.2.0.1        
## [23] kableExtra_1.3.1            dplyr_1.0.2                
## [25] lubridate_1.7.9.2           leaflet_2.0.3              
## [27] yaml_2.2.1                  fontawesome_0.1.0          
## [29] captioner_2.2.3             bookdown_0.21              
## [31] knitr_1.30                 
## 
## loaded via a namespace (and not attached):
##  [1] nlme_3.1-149           bitops_1.0-6           bit64_4.0.5           
##  [4] webshot_0.5.2          RColorBrewer_1.1-2     progress_1.2.2        
##  [7] httr_1.4.2             tools_4.0.3            R6_2.5.0              
## [10] DBI_1.1.0              mgcv_1.8-33            colorspace_2.0-0      
## [13] withr_2.3.0            gridExtra_2.3          prettyunits_1.1.1     
## [16] tidyselect_1.1.0       curl_4.3               bit_4.0.4             
## [19] compiler_4.0.3         rvest_0.3.6            xml2_1.3.2            
## [22] DelayedArray_0.16.0    labeling_0.4.2         genefilter_1.72.0     
## [25] askpass_1.1            rappdirs_0.3.1         digest_0.6.27         
## [28] rmarkdown_2.5          XVector_0.30.0         pkgconfig_2.0.3       
## [31] htmltools_0.5.0        dbplyr_2.0.0           htmlwidgets_1.5.2     
## [34] rlang_0.4.9            rstudioapi_0.13        RSQLite_2.2.1         
## [37] generics_0.1.0         farver_2.0.3           jsonlite_1.7.1        
## [40] crosstalk_1.1.0.1      BiocParallel_1.24.1    RCurl_1.98-1.2        
## [43] magrittr_2.0.1         GenomeInfoDbData_1.2.4 Matrix_1.2-18         
## [46] Rcpp_1.0.5             munsell_0.5.0          lifecycle_0.2.0       
## [49] stringi_1.5.3          zlibbioc_1.36.0        BiocFileCache_1.14.0  
## [52] grid_4.0.3             blob_1.2.1             crayon_1.3.4          
## [55] lattice_0.20-41        splines_4.0.3          annotate_1.68.0       
## [58] hms_0.5.3              locfit_1.5-9.4         pillar_1.4.7          
## [61] rjson_0.2.20           geneplotter_1.68.0     fastmatch_1.1-0       
## [64] XML_3.99-0.5           glue_1.4.2             evaluate_0.14         
## [67] data.table_1.13.2      vctrs_0.3.5            openssl_1.4.3         
## [70] gtable_0.3.0           purrr_0.3.4            tidyr_1.1.2           
## [73] assertthat_0.2.1       xfun_0.19              xtable_1.8-4          
## [76] survival_3.2-7         viridisLite_0.3.0      tibble_3.0.4          
## [79] AnnotationDbi_1.52.0   memoise_1.1.0          ellipsis_0.3.1