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.
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
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
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
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"
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"
# 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] 146 45 52 65 97 173 105 153 32 16
## [1] 10
## [1] 884
## [1] 88.4
## [1] 81
## [1] 16
## [1] 4.983607 3.806662 3.951244 4.174387 4.574711 5.153292 4.653960 5.030438
## [9] 3.465736 2.772589
## [1] 2.552668e+63 3.493427e+19 3.831008e+22 1.694889e+28 1.338335e+42
## [6] 1.358143e+75 3.989520e+45 2.799341e+66 7.896296e+13 8.886111e+06
## [1] 12.083046 6.708204 7.211103 8.062258 9.848858 13.152946 10.246951
## [8] 12.369317 5.656854 4.000000
## [1] 146 45 52 65 97 173 105 153 32 16
## [1] 16 32 45 52 65 97 105 146 153 173
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
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
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()
.
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)
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")
Input and output of data and images is an important aspect with data analysis.
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.
Let’s take a look at saving plots.
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()
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)
?function
to get function documentation??bla
to search for a functionargs(function)
to get the arguments to a function## R version 4.1.3 (2022-03-10)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 18.04.6 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] stats4 stats graphics grDevices utils datasets methods
## [8] base
##
## other attached packages:
## [1] stringr_1.5.0 fgsea_1.20.0
## [3] enrichR_3.1 rafalib_1.0.0
## [5] biomaRt_2.50.3 pvclust_2.2-0
## [7] pheatmap_1.0.12 edgeR_3.36.0
## [9] limma_3.50.3 DESeq2_1.34.0
## [11] SummarizedExperiment_1.24.0 Biobase_2.54.0
## [13] MatrixGenerics_1.6.0 matrixStats_0.63.0
## [15] GenomicRanges_1.46.1 GenomeInfoDb_1.30.1
## [17] IRanges_2.28.0 S4Vectors_0.32.4
## [19] BiocGenerics_0.40.0 ggplot2_3.4.1
## [21] formattable_0.2.1 kableExtra_1.3.4
## [23] dplyr_1.1.0 lubridate_1.9.2
## [25] yaml_2.3.7 fontawesome_0.5.0.9000
## [27] captioner_2.2.3 bookdown_0.33
## [29] knitr_1.42
##
## loaded via a namespace (and not attached):
## [1] colorspace_2.1-0 rjson_0.2.21 ellipsis_0.3.2
## [4] XVector_0.34.0 rstudioapi_0.14 farver_2.1.1
## [7] bit64_4.0.5 AnnotationDbi_1.56.2 fansi_1.0.4
## [10] xml2_1.3.3 splines_4.1.3 cachem_1.0.7
## [13] geneplotter_1.72.0 jsonlite_1.8.4 annotate_1.72.0
## [16] dbplyr_2.3.1 png_0.1-8 compiler_4.1.3
## [19] httr_1.4.5 Matrix_1.4-0 fastmap_1.1.1
## [22] cli_3.6.0 htmltools_0.5.4 prettyunits_1.1.1
## [25] tools_4.1.3 gtable_0.3.1 glue_1.6.2
## [28] GenomeInfoDbData_1.2.7 rappdirs_0.3.3 fastmatch_1.1-3
## [31] Rcpp_1.0.10 jquerylib_0.1.4 vctrs_0.5.2
## [34] Biostrings_2.62.0 svglite_2.1.1 nlme_3.1-155
## [37] xfun_0.37 rvest_1.0.3 timechange_0.2.0
## [40] lifecycle_1.0.3 XML_3.99-0.13 zlibbioc_1.40.0
## [43] scales_1.2.1 hms_1.1.2 parallel_4.1.3
## [46] RColorBrewer_1.1-3 curl_5.0.0 gridExtra_2.3
## [49] memoise_2.0.1 sass_0.4.5 stringi_1.7.12
## [52] RSQLite_2.3.0 highr_0.10 genefilter_1.76.0
## [55] filelock_1.0.2 BiocParallel_1.28.3 rlang_1.0.6
## [58] pkgconfig_2.0.3 systemfonts_1.0.4 bitops_1.0-7
## [61] evaluate_0.20 lattice_0.20-45 purrr_1.0.1
## [64] htmlwidgets_1.6.1 labeling_0.4.2 bit_4.0.5
## [67] tidyselect_1.2.0 magrittr_2.0.3 R6_2.5.1
## [70] generics_0.1.3 DelayedArray_0.20.0 DBI_1.1.3
## [73] pillar_1.8.1 withr_2.5.0 mgcv_1.8-39
## [76] survival_3.2-13 KEGGREST_1.34.0 RCurl_1.98-1.10
## [79] tibble_3.2.0 crayon_1.5.2 utf8_1.2.3
## [82] BiocFileCache_2.2.1 rmarkdown_2.20 progress_1.2.2
## [85] locfit_1.5-9.7 grid_4.1.3 data.table_1.14.8
## [88] blob_1.2.3 digest_0.6.31 webshot_0.5.4
## [91] xtable_1.8-4 tidyr_1.3.0 munsell_0.5.0
## [94] viridisLite_0.4.1 bslib_0.4.2