-
Notifications
You must be signed in to change notification settings - Fork 14
/
lab_r.Rmd
486 lines (340 loc) · 9.54 KB
/
lab_r.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
---
title: "Intro to R"
subtitle: "Workshop on RNA-Seq"
output:
bookdown::html_document2:
highlight: textmate
toc: true
toc_float:
collapsed: true
smooth_scroll: true
print: false
toc_depth: 4
number_sections: true
df_print: default
code_folding: none
self_contained: false
keep_md: false
encoding: 'UTF-8'
css: "assets/lab.css"
include:
after_body: assets/footer-lab.html
---
```{r,child="assets/header-lab.Rmd"}
```
```{r,include=FALSE}
# data handling
library(dplyr)
#library(tidyr)
#library(stringr)
# plotting
library(ggplot2)
library(biomaRt) # annotation
library(DESeq2) # rna-seq
library(edgeR) # rna-seq
```
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.
# Assignment operator
Variables are assigned usually using the `<-` operator. The `=` operator also works in a similar way for most part.
```{r}
x <- 4
x = 4
x
```
# Arithmetic operators
The commonly used arithmetic operators are shown below returning a number.
```{r}
x <- 4
y <- 2
# add
x + y
# subtract
x - y
# multiply
x * y
# divide
x / y
# modulus
x %% y
# power
x ^ y
```
# Logical operators
Logical operators return a logical `TRUE` or `FALSE`.
```{r}
# 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
```
# Data types
```{r}
class(1)
class("hello")
class(T)
```
```{r}
x <- c(2,3,4,5,6)
y <- c("a","c","d","e")
z <- factor(c("a","c","d","e"))
class(z)
```
```{r}
x <- matrix(c(2,3,4,5,6,7),nrow=3,ncol=2)
class(x)
str(x)
```
```{r,results="markup"}
dfr <- data.frame(x = 1:3, y = c("a", "b", "c"))
print(dfr)
class(dfr)
str(dfr)
```
# Accessors
Vectors positions can be accessed using `[]`. R follows 1-based indexing.
```{r}
x <- c(2,3,4,5,6)
x
x[2]
```
Dataframe or matrix positions can be accessed using `[]` specifying row and column like `[row,column]`.
```{r}
dfr <- data.frame(x = 1:3, y = c("a", "b", "c"))
dfr
dfr[1,]
dfr[,1]
dfr[2,2]
```
# Functions
```{r}
# 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)
```
Some useful string functions.
```{r}
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)
```
Some general functions
```{r}
print("hello")
print("world")
cat("hello")
cat(" world")
cat("\nhello\nworld")
```
# Merging
Two strings can be joined together using `paste()`.
```{r}
a <- "sunny"
b <- "day"
paste(a, b)
paste(a, b, sep="-")
```
The function `c()` is used to concatenate objects.
```{r}
a <- "sunny"
b <- "day"
c(a,b)
```
The function `cbind()` is used to join two dataframes column-wise.
```{r}
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)
```
Similarily, `rbind()` is used to join two dataframes row-wise.
```{r}
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)
```
Two dataframes can be merged based on a shared column using the `merge()` function.
```{r}
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)
```
# Packages
R packages extend the functionality of base R. R packages are stored in repositories of which the most commonly used is called [CRAN](https://cran.r-project.org/) (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.
```{r,eval=FALSE}
install.packages("ggplot2",dependencies=TRUE)
```
Packages on BioConductor can be installed as follows:
```{r,eval=FALSE}
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"`.
```{r,eval=FALSE}
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()`.
# Graphics
## 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.
```{r}
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.
```{r}
plot(dfr$a,dfr$b)
```
This is probably the simplest and most basic plots. We can modify the x and y axis labels.
```{r}
plot(dfr$a,dfr$b,xlab="Variable a",ylab="Variable b")
```
We can change the point to a line.
```{r}
plot(dfr$a,dfr$b,xlab="Variable a",ylab="Variable b",type="b")
```
Let's add a categorical column to our dataframe.
```{r}
dfr$cat <- rep(c("C1","C2"),each=5)
```
And then colour the points by category.
```{r}
# 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.
```{r}
ldr <- data.frame(a=letters[1:10],b=sample(1:50,10))
barplot(ldr$b,names.arg=ldr$a)
```
## 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.
```{r}
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.
```{r}
ggplot(ldr,aes(x=a,y=b))+
geom_bar(stat="identity")
```
# Input/Output
Input and output of data and images is an important aspect with data analysis.
## 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**.
```{r,eval=FALSE}
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.
```{r,eval=FALSE}
head(dfr)
```
```{r,eval=FALSE}
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.
```{r,eval=FALSE}
dfr1 <- dfr[dfr$Species == "setosa",]
```
And we can write this as a text file.
```{r,eval=FALSE}
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.
## Images
Let's take a look at saving plots.
## 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.
```{r,eval=FALSE}
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()
```
## 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.
```{r,eval=FALSE}
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.
```{r,eval=FALSE}
ggsave(filename="plot-ggplot-2.png",plot=p)
```
# 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](http://www.cookbook-r.com/): General purpose reference.
- [Quick R](https://www.statmethods.net/): General purpose reference.
- [Stackoverflow](https://stackoverflow.com/): Online community to find solutions to your problems.
# Session info
```{r,echo=FALSE}
sessionInfo()
```
***