forked from bobthecat/R-Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathR_for_gene_exp.R
640 lines (515 loc) · 19.4 KB
/
R_for_gene_exp.R
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
###################################################
### chunk number 1:
###################################################
#line 71 "R_for_gene_exp.Rnw"
options(width=80, continue=" ")
###################################################
### chunk number 2: loading the libraries
###################################################
#line 83 "R_for_gene_exp.Rnw"
## load package library
library(GEOquery)
library(affy)
library(RColorBrewer)
library(affyPLM)
library(mouse4302cdf)
###################################################
### chunk number 3: importAffy
###################################################
#line 107 "R_for_gene_exp.Rnw"
library(affy)
## Import the Affymetrix data in R
da <- ReadAffy(celfile.path="./GSE12499/", compress=TRUE)
###################################################
### chunk number 4: pdata
###################################################
#line 114 "R_for_gene_exp.Rnw"
## Information about your data
da
## ADDING SOME PHENODATA
# what are the phenoData by default
pData(da)
#
sampleNames(da)
###################################################
### chunk number 5: import
###################################################
#line 126 "R_for_gene_exp.Rnw"
URL <- "http://www.stanford.edu/~druau/treatment.txt"
pd <- read.table(URL, sep='\t', header=TRUE)
pd
###################################################
### chunk number 6: pdata2
###################################################
#line 133 "R_for_gene_exp.Rnw"
pData(da) <- pd
pData(da)
sampleNames(da) <- pd[,1]
###################################################
### chunk number 7: pset
###################################################
#line 148 "R_for_gene_exp.Rnw"
pset <- fitPLM(da)
###################################################
### chunk number 8: img.test
###################################################
#line 152 "R_for_gene_exp.Rnw"
img.Test <- function(batch,pset,x) {
par(mfrow = c(2,2))
image(batch[,x])
image(pset, type = "weights", which = x)
image(pset, type = "resids", which = x)
image(pset, type = "sign.resids", which = x)
}
###################################################
### chunk number 9: fig2plot
###################################################
#line 201 "R_for_gene_exp.Rnw"
cols <- brewer.pal(12, "Set3")
Mbox(pset, col = cols, main ="RLE (Relative Log Expression)",
xlab="Assuming that the majority of the gene are not changing\n Ideally these boxes would have small spread and be centered at M=0")
###################################################
### chunk number 10: fig2
###################################################
#line 208 "R_for_gene_exp.Rnw"
#line 201 "R_for_gene_exp.Rnw"
cols <- brewer.pal(12, "Set3")
Mbox(pset, col = cols, main ="RLE (Relative Log Expression)",
xlab="Assuming that the majority of the gene are not changing\n Ideally these boxes would have small spread and be centered at M=0")
#line 209 "R_for_gene_exp.Rnw"
###################################################
### chunk number 11: fig3plot
###################################################
#line 219 "R_for_gene_exp.Rnw"
boxplot(pset, col=cols, main= "NUSE (Normalized Unscaled Standard Error)",
xlab="High values of median NUSE are indicative of a problematic array")
###################################################
### chunk number 12: fig3
###################################################
#line 225 "R_for_gene_exp.Rnw"
#line 219 "R_for_gene_exp.Rnw"
boxplot(pset, col=cols, main= "NUSE (Normalized Unscaled Standard Error)",
xlab="High values of median NUSE are indicative of a problematic array")
#line 226 "R_for_gene_exp.Rnw"
###################################################
### chunk number 13: fig4plot
###################################################
#line 236 "R_for_gene_exp.Rnw"
RNAdeg <- AffyRNAdeg(da)
plotAffyRNAdeg(RNAdeg, cols=cols)
legend("topleft", sampleNames(da), lty=1, col=cols)
box()
###################################################
### chunk number 14: fig4
###################################################
#line 244 "R_for_gene_exp.Rnw"
#line 236 "R_for_gene_exp.Rnw"
RNAdeg <- AffyRNAdeg(da)
plotAffyRNAdeg(RNAdeg, cols=cols)
legend("topleft", sampleNames(da), lty=1, col=cols)
box()
#line 245 "R_for_gene_exp.Rnw"
###################################################
### chunk number 15: loading agilent
###################################################
#line 266 "R_for_gene_exp.Rnw"
library(Agi4x44PreProcess)
targets <- read.targets(infile='mRNA_labelling.txt')
###################################################
### chunk number 16: read Agilent data eval=FALSE
###################################################
## #line 271 "R_for_gene_exp.Rnw"
## ## read the data in
## da <- read.AgilentFE(targets, makePLOT=FALSE)
##
## ## background correction and normalization
## da.n <- BGandNorm(da, BGmethod = "normexp", NORMmethod = "quantile", foreground = "ProcessedSignal", background = "BGUsed", offset = 50, makePLOTpre = FALSE, makePLOTpost = FALSE)
## ## Data are log-2 transformed see ?BGandNorm
###################################################
### chunk number 17: unspecific filtering eval=FALSE
###################################################
## #line 320 "R_for_gene_exp.Rnw"
## ## Unspecific filtering
## da.f <- filter.probes(da.n,
## control=TRUE,
## wellaboveBG=TRUE,
## isfound=TRUE,
## wellaboveNEG=TRUE,
## sat=TRUE,
## PopnOL=TRUE,
## NonUnifOL=T,
## nas=TRUE,
## limWellAbove=75,
## limISF=75,
## limNEG=75,
## limSAT=75,
## limPopnOL=75,
## limNonUnifOL=75,
## limNAS=100,
## makePLOT=F,annotation.package="HsAgilentDesign026652.db",flag.counts=T,targets)
##
## ## Summarize signal
## da.s <- summarize.probe(da.f, makePLOT=FALSE, targets)
##
## rownames(targets) <- colnames(da.s)
##
## ## building a expression set
## da.eset <- build.eset(da.s, targets, makePLOT = FALSE, annotation.package = "HsAgilentDesign026652.db")
###################################################
### chunk number 18: RMA
###################################################
#line 400 "R_for_gene_exp.Rnw"
da.rma <- rma(da)
###################################################
### chunk number 19: exprs
###################################################
#line 404 "R_for_gene_exp.Rnw"
da.eset <- exprs(da.rma)
dim(da.eset)
colnames(da.eset)
###################################################
### chunk number 20: RP
###################################################
#line 432 "R_for_gene_exp.Rnw"
library(RankProd)
cl <- c(rep(0,3), rep(1,4))
options(width=100)
head(da.eset[,c(4:6, 7:10)])
options(width=80)
da.rp <- RP(da.eset[,c(4:6, 7:10)], cl=cl, logged=TRUE, num.perm=100, plot=FALSE, rand=5432)
###################################################
### chunk number 21: extracting_gene
###################################################
#line 443 "R_for_gene_exp.Rnw"
library(mouse4302.db)
gnames <- as.vector(unlist(as.list(mouse4302SYMBOL)))
r.nsc.1fipsc <- topGene(da.rp, cutoff = 0.05, method = "pfp", logged = TRUE,
logbase = 2, gene.names=gnames)
# The genes significantly up-regulated
head(r.nsc.1fipsc$Table1, 20)
# How many genes are in table 2
dim(r.nsc.1fipsc$Table1)
# The genes significantly down-regulated
head(r.nsc.1fipsc$Table2, 20)
# how many genes are in table 2
dim(r.nsc.1fipsc$Table2)
###################################################
### chunk number 22: export
###################################################
#line 461 "R_for_gene_exp.Rnw"
# up reg
x <- r.nsc.1fipsc$Table1
# replace the fold change value by their log2 conterpart
x[,3] <- log2(1/x[,3])
write.table(x, file = "NSC_vs_1F_iPSC_up.txt", sep = "\t", quote = FALSE)
# down reg
x <- r.nsc.1fipsc$Table2
# replace the fold change value by their log2 conterpart
x[,3] <- log2(1/x[,3])
write.table(x, file = "NSC_vs_1F_iPSC_down.txt", sep = "\t", quote = FALSE)
###################################################
### chunk number 23: gene list 2
###################################################
#line 500 "R_for_gene_exp.Rnw"
library(RankProd)
library(affy)
cl <- c(rep(0,4), rep(1,3))
da.rp <- RP(da.eset[,c(7:10, 1:3)], cl=cl, logged=TRUE, num.perm=100, plot=FALSE, rand=5432)
###################################################
### chunk number 24: annot_package
###################################################
#line 508 "R_for_gene_exp.Rnw"
## ANNOTATION PACKAGE
library(mouse4302.db)
gnames <- as.vector(unlist(as.list(mouse4302SYMBOL)))
###################################################
### chunk number 25: genes
###################################################
#line 515 "R_for_gene_exp.Rnw"
r.nsc.nsc_1f <- topGene(da.rp, cutoff = 0.05, method = "pfp", logged = TRUE, logbase = 2, gene.names=gnames)
# The genes significantly up-regulated
head(r.nsc.nsc_1f$Table1, 20)
# how many genes are in table 2
dim(r.nsc.nsc_1f$Table1)
# The genes significantly down-regulated
head(r.nsc.nsc_1f$Table2, 20)
# how many genes are in table 2
dim(r.nsc.nsc_1f$Table2)
###################################################
### chunk number 26: fig5plot
###################################################
#line 546 "R_for_gene_exp.Rnw"
library(bioDist)
## Pearson correlation dissimilarity
d <- cor.dist(t(da.eset)) # careful here don't forget to transpose your matrix
dim(as.matrix(d))
#####################################################
## HIERARCHICAL CLUSTERING
#####################################################
## dendrogram
hc = hclust(d, method = "average")
plot(hc, labels = colnames(da.eset), main = "Hier. clust. Pearson", hang=-1)
# effect of the hang = -1
plot(hc, labels = colnames(da.eset), main = "Hier. clust. Pearson")
###################################################
### chunk number 27: fig5
###################################################
#line 563 "R_for_gene_exp.Rnw"
#line 546 "R_for_gene_exp.Rnw"
library(bioDist)
## Pearson correlation dissimilarity
d <- cor.dist(t(da.eset)) # careful here don't forget to transpose your matrix
dim(as.matrix(d))
#####################################################
## HIERARCHICAL CLUSTERING
#####################################################
## dendrogram
hc = hclust(d, method = "average")
plot(hc, labels = colnames(da.eset), main = "Hier. clust. Pearson", hang=-1)
# effect of the hang = -1
plot(hc, labels = colnames(da.eset), main = "Hier. clust. Pearson")
#line 564 "R_for_gene_exp.Rnw"
###################################################
### chunk number 28: fig6_1
###################################################
#line 573 "R_for_gene_exp.Rnw"
library(graphics)
d <- cor.dist(as.matrix(USArrests))
# Let's compare the linkage methods
par(mfrow = c(2,1))
hc <- hclust(d, "average")
plot(hc, main = "AVERAGE", hang = -1)
hc = hclust(d, method = "single")
plot(hc, main = "SINGLE", hang=-1)
###################################################
### chunk number 29: fig6_2
###################################################
#line 585 "R_for_gene_exp.Rnw"
hc = hclust(d, method = "complete")
plot(hc, main = "COMPLETE", hang=-1)
hc = hclust(d, method = "ward")
plot(hc, main = "WARD", hang=-1)
# ressetting the graphic device layout to default
par(mfrow = c(1,1))
###################################################
### chunk number 30: fig6_1
###################################################
#line 597 "R_for_gene_exp.Rnw"
#line 573 "R_for_gene_exp.Rnw"
library(graphics)
d <- cor.dist(as.matrix(USArrests))
# Let's compare the linkage methods
par(mfrow = c(2,1))
hc <- hclust(d, "average")
plot(hc, main = "AVERAGE", hang = -1)
hc = hclust(d, method = "single")
plot(hc, main = "SINGLE", hang=-1)
#line 598 "R_for_gene_exp.Rnw"
###################################################
### chunk number 31: fig6_2
###################################################
#line 607 "R_for_gene_exp.Rnw"
#line 585 "R_for_gene_exp.Rnw"
hc = hclust(d, method = "complete")
plot(hc, main = "COMPLETE", hang=-1)
hc = hclust(d, method = "ward")
plot(hc, main = "WARD", hang=-1)
# ressetting the graphic device layout to default
par(mfrow = c(1,1))
#line 608 "R_for_gene_exp.Rnw"
###################################################
### chunk number 32: fig7plot
###################################################
#line 616 "R_for_gene_exp.Rnw"
library(cluster)
hc.d <- diana(d)
plot(hc.d, which.plots=2, main = "DIVISIVE HIERARCHICAL CLUSTERING")
###################################################
### chunk number 33: fig7
###################################################
#line 624 "R_for_gene_exp.Rnw"
#line 616 "R_for_gene_exp.Rnw"
library(cluster)
hc.d <- diana(d)
plot(hc.d, which.plots=2, main = "DIVISIVE HIERARCHICAL CLUSTERING")
#line 625 "R_for_gene_exp.Rnw"
###################################################
### chunk number 34: fig8plot
###################################################
#line 635 "R_for_gene_exp.Rnw"
library(gplots)
library(RColorBrewer)
library(bioDist)
# First we build a color palette
hmcol = colorRampPalette(brewer.pal(10, "RdBu"))(256)
# Recomputing the dissimilarity matrix for the gene expression values
d <- cor.dist(t(da.eset))
## Heatmap for the samples
heatmap.2(as.matrix(d),
distfun=function(x){as.dist(x)},
hclustfun=function(m){hclust(m, method="average")},
symm=F, col=hmcol, trace='none', notecol='black',
denscol='black', notecex=0.8, dendrogram="column")
###################################################
### chunk number 35: fig8
###################################################
#line 653 "R_for_gene_exp.Rnw"
#line 635 "R_for_gene_exp.Rnw"
library(gplots)
library(RColorBrewer)
library(bioDist)
# First we build a color palette
hmcol = colorRampPalette(brewer.pal(10, "RdBu"))(256)
# Recomputing the dissimilarity matrix for the gene expression values
d <- cor.dist(t(da.eset))
## Heatmap for the samples
heatmap.2(as.matrix(d),
distfun=function(x){as.dist(x)},
hclustfun=function(m){hclust(m, method="average")},
symm=F, col=hmcol, trace='none', notecol='black',
denscol='black', notecex=0.8, dendrogram="column")
#line 654 "R_for_gene_exp.Rnw"
###################################################
### chunk number 36: fig9plot
###################################################
#line 662 "R_for_gene_exp.Rnw"
r.nsc.nsc_1f <- topGene(da.rp, cutoff = 0.001, method = "pfp", logged = TRUE, logbase = 2, gene.names=gnames)
heatmap.2(da.eset[r.nsc.nsc_1f$Table1[,1],],
distfun=function(x){as.dist(1 - cor(t(x), use = "complete.obs", method ="pearson"))},
hclustfun=function(m){hclust(m, method="average")},
symm=F, col=hmcol, trace='none', notecol='black',
denscol='black', notecex=0.8, dendrogram="column")
###################################################
### chunk number 37: fig9
###################################################
#line 672 "R_for_gene_exp.Rnw"
#line 662 "R_for_gene_exp.Rnw"
r.nsc.nsc_1f <- topGene(da.rp, cutoff = 0.001, method = "pfp", logged = TRUE, logbase = 2, gene.names=gnames)
heatmap.2(da.eset[r.nsc.nsc_1f$Table1[,1],],
distfun=function(x){as.dist(1 - cor(t(x), use = "complete.obs", method ="pearson"))},
hclustfun=function(m){hclust(m, method="average")},
symm=F, col=hmcol, trace='none', notecol='black',
denscol='black', notecex=0.8, dendrogram="column")
#line 673 "R_for_gene_exp.Rnw"
###################################################
### chunk number 38: over-representation
###################################################
#line 757 "R_for_gene_exp.Rnw"
library(GOstats)
library(mouse4302.db)
library(RankProd)
r.nsc.nsc_1f <- topGene(da.rp, cutoff = 0.001, method = "pfp",
logged = TRUE, logbase = 2, gene.names = rownames(da.rp$AveFC))
uniqueId <- mouse4302ENTREZID
entrezUniverse <- unique(as.character(uniqueId))
# Convert our list of Affymetrix probe IDs to
# NCBI Entrez gene ID
g.list <- c(rownames(r.nsc.nsc_1f$Table1), rownames(r.nsc.nsc_1f$Table2))
ourlist <- mouse4302ENTREZID[g.list]
ourlist <- unique(as.character(ourlist))
# creating the GOHyperGParams object
params = new("GOHyperGParams", geneIds=ourlist,
universeGeneIds=entrezUniverse, annotation='mouse4302.db',
ontology="BP", pvalueCutoff=0.001, conditional=FALSE, testDirection="over")
# running the test
mfhyper = hyperGTest(params)
###################################################
### chunk number 39: hypergeo
###################################################
#line 783 "R_for_gene_exp.Rnw"
mfhyper
head(summary(mfhyper))
# grabbing detail of a GO category
GOTERM[["GO:0032502"]]
# Information on the Directed Acyclic Graph (DAG)
goDag(mfhyper)
# how many gene were mapped in the end?
geneMappedCount(mfhyper)
# how many genes are in the universe
universeMappedCount(mfhyper)
# html output
htmlReport(mfhyper, file="BP_list_significant.html")
###################################################
### chunk number 40: fig13plot
###################################################
#line 805 "R_for_gene_exp.Rnw"
library(Rgraphviz)
g1 <- GOGraph(head(summary(mfhyper))$GOBPID, GOBPPARENTS)
plot(g1)
# display the label in the nodes
my.labels <- vector()
for(i in 1:length(slot(g1, "nodes"))){
my.labels[i] <- Term(get(slot(g1, "nodes")[[i]], GOTERM))
}
my.labels
nodattr <- makeNodeAttrs(g1, label=my.labels,
shape = "ellipse", fillcolor = "#f2f2f2", fixedsize = FALSE)
plot(g1, nodeAttrs = nodattr)
###################################################
### chunk number 41: fig13
###################################################
#line 824 "R_for_gene_exp.Rnw"
#line 805 "R_for_gene_exp.Rnw"
library(Rgraphviz)
g1 <- GOGraph(head(summary(mfhyper))$GOBPID, GOBPPARENTS)
plot(g1)
# display the label in the nodes
my.labels <- vector()
for(i in 1:length(slot(g1, "nodes"))){
my.labels[i] <- Term(get(slot(g1, "nodes")[[i]], GOTERM))
}
my.labels
nodattr <- makeNodeAttrs(g1, label=my.labels,
shape = "ellipse", fillcolor = "#f2f2f2", fixedsize = FALSE)
plot(g1, nodeAttrs = nodattr)
#line 825 "R_for_gene_exp.Rnw"
###################################################
### chunk number 42: PAM
###################################################
#line 835 "R_for_gene_exp.Rnw"
library(cluster)
library(lattice)
library(bioDist)
# K-means
# we want to find the different type of gene expression pattern among
# the genes significantly regulated
sub.da <- da.eset[g.list,]
# compute the correlation matrix between the genes
d <- cor.dist(sub.da)
# Cluster the genes for k = 3
g.pam <- pam(d, k = 3)
###################################################
### chunk number 43: fig14plot
###################################################
#line 850 "R_for_gene_exp.Rnw"
x <- vector()
for(i in 3:20){
g.pam <- pam(d, k = i)
x[i] <- g.pam$silinfo$avg.width
}
plot(x, xlab = 'K (cluster number requested)', ylab = 'average silhouette width')
###################################################
### chunk number 44: fig14
###################################################
#line 861 "R_for_gene_exp.Rnw"
#line 850 "R_for_gene_exp.Rnw"
x <- vector()
for(i in 3:20){
g.pam <- pam(d, k = i)
x[i] <- g.pam$silinfo$avg.width
}
plot(x, xlab = 'K (cluster number requested)', ylab = 'average silhouette width')
#line 862 "R_for_gene_exp.Rnw"
###################################################
### chunk number 45: fig15plot
###################################################
#line 870 "R_for_gene_exp.Rnw"
g.pam <- pam(d, k = 8)
# transform sub.da
x <- data.frame()
for(i in 1:ncol(sub.da)){
x <- rbind(x, data.frame(gene.expression = sub.da[,i], cell.type = colnames(sub.da)[i]))
}
# plot the data
df <- data.frame(cluster = as.vector(g.pam$clustering), x)
bwplot(gene.expression ~ cell.type | cluster, data = df)