forked from raphg/Biostat-578
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLab_Searching_GEO.Rmd
516 lines (387 loc) · 15 KB
/
Lab_Searching_GEO.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
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
---
title: "Searching GEO"
author: "Brian High"
date: "2/6/2015"
output:
ioslides_presentation:
fig_caption: yes
fig_retina: 1
keep_md: yes
smaller: yes
---
## Setting up some options
Let's first turn on the cache for increased performance and improved styling.
```{r, cache=FALSE}
# Set some global knitr options
library("knitr")
opts_chunk$set(tidy=TRUE, tidy.opts=list(blank=FALSE, width.cutoff=60),
cache=FALSE, messages=FALSE)
```
Load the `pander` package so we can make nicer table listings with `pandoc.table`.
```{r}
suppressMessages(library(pander))
```
## Prepare for HW2
We will need to query the GEOmetadb database. Today we will explore this
database and practice various ways to query it.
## Load the `GEOmetadb` package
First we load the `GEOmetadb` library.
```{r}
suppressMessages(library(GEOmetadb))
```
Let's also view the available methods.
```{r}
ls("package:GEOmetadb")
```
## Download the GEO database
We should have already downloaded this database when viewing the lecture slides.
```{r}
## This will download the entire database, so can be slow
if(!file.exists("GEOmetadb.sqlite"))
{
# Download database only if it's not done already
getSQLiteFile()
}
```
## List tables with `SQL`
In `SQL`, you can query the database structure with ordinary `SQL` commands.
```{r}
geo_con <- dbConnect(SQLite(), 'GEOmetadb.sqlite')
dbGetQuery(geo_con, "SELECT name FROM sqlite_master WHERE type='table';")
```
## List `gse` fields with `SQL`
The `PRAGMA` command is a standard `SQLite` command.
```{r}
dbGetQuery(geo_con, "PRAGMA table_info(gse);")
```
## List tables with `dbListTables`
Instead of using `SQL` commands, we can list tables and fields with functions
from the `GEOmetadb` package.
```{r}
geo_con <- dbConnect(SQLite(), 'GEOmetadb.sqlite')
dbListTables(geo_con)
```
```{r}
dbListFields(geo_con, 'gse')
```
## Explore `gse`
```{r}
columnDescriptions()[1:5,]
```
## Load library `data.table`
This will provide us with some practice querying with data.table.
```{r}
suppressMessages(library(data.table))
```
## Explore `gse` with `data.table`
```{r}
cd <- as.data.table(columnDescriptions())
cd[TableName=="gse", FieldName]
```
## List `gse` columns with `pandoc.table`
```{r}
gsefields <- as.data.frame(
cd[TableName=="gse" &
FieldName %in% c("gse","title","pubmed_id","summary","contact")])
pandoc.table(gsefields, style="grid")
```
## Explore `gpl`
```{r}
cd[TableName=="gpl", FieldName]
```
## Explore columns in `gpl`
```{r}
gplfields <- as.data.frame(
cd[TableName=="gpl" &
FieldName %in% c("gpl","organism","manufacturer")])
pandoc.table(gplfields, style="grid")
```
## Explore `gse_gpl`
```{r}
cd[TableName=="gse_gpl", FieldName]
```
## Explore columns in `gse_gpl`
Why are there only two fields in this table? What is this table for?
```{r}
gse_gplfields <- as.data.frame(cd[TableName=="gse_gpl"])
pandoc.table(gse_gplfields, style="grid")
```
## List "title" fields with `pandoc.table`
Why do many tables include a "title" field? Are the titles the same?
```{r}
gsefields <- as.data.frame(
cd[FieldName == "title"])
pandoc.table(gsefields, style="grid")
```
## List "contact" field structure
Let's look at some records in `gse`. What does a "contact" look like?
```{r}
query <- "SELECT contact FROM gse LIMIT 1;"
res <- dbGetQuery(geo_con, query)
strsplit(res$contact, '\t')
```
## Find manufacturer data
Query the manufacturers with a `SQL` command, listed with `data.table`...
```{r, tidy=FALSE}
manu <- data.table(dbGetQuery(geo_con,
"SELECT DISTINCT manufacturer FROM gpl ORDER BY manufacturer ASC;"))
manu[,list(length(manufacturer)), by=manufacturer]
```
## Our `SQL` command
We just wanted a list of manufacturers so the `SQL` query is:
```
SELECT DISTINCT manufacturer FROM gpl
ORDER BY manufacturer ASC;
```
However, since we also grouped `by=manufacturer` in our `data.table`, we could
have simply used the `SQL` query:
```
SELECT manufacturer FROM gpl;
```
Let's try that...
## Find manufacturer data
Query the manufacturers with a simpler `SQL` command ... grouping with `by` and
ordering with `setkey` in `data.table`...
```{r, tidy=FALSE}
manu <- data.table(dbGetQuery(geo_con,
"SELECT manufacturer FROM gpl;"))
setkey(manu, manufacturer)
manu[,list(length(manufacturer)), by=manufacturer]
```
## Finding data with a `join`
To get supplementary file names ending with `CEL.gz` (case-insensitive) from
only manufacturer Affymetrix, we need to `join` the `gsm` and `gpl` tables.
```
SELECT
gpl.bioc_package,
gsm.title,
gsm.series_id,
gsm.gpl,
gsm.supplementary_file
FROM gsm
JOIN gpl ON gsm.gpl=gpl.gpl
WHERE gpl.manufacturer='Affymetrix'
AND gsm.supplementary_file like '%CEL.gz';
```
## Now let's run that query
```{r, tidy=FALSE}
query<-"SELECT
gpl.bioc_package,
gsm.title,
gsm.series_id,
gsm.gpl,
gsm.supplementary_file
FROM gsm
JOIN gpl ON gsm.gpl=gpl.gpl
WHERE gpl.manufacturer='Affymetrix'
AND gsm.supplementary_file like '%CEL.gz';"
res <- dbGetQuery(geo_con, query)
head(res, 3)
```
## Why did we need a `join`?
The
[GEOmetadb database](http://gbnci.abcc.ncifcrf.gov/geo/geo_help.php),
is a [relational database](http://en.wikipedia.org/wiki/Relational_database).
There are several tables which can be linked on common fields.
Since each table
contains data for only one type of record, tables must be linked to search for
fields pertaining to the various types of records.
We join on the common fields,
called [keys](http://en.wikipedia.org/wiki/Relational_database#Primary_key).
## Table Relationships of `GEOmetadb`
![Table Relationships](http://gbnci.abcc.ncifcrf.gov/geo/images/GEOmetadb_diagram.png)
Source: [Help: GEOmetadb Application, Meltzerlab/GB/CCR/NCI/NIH ©2008](http://gbnci.abcc.ncifcrf.gov/geo/geo_help.php)
## Keys of `GEOmetadb`
```
+------------+-------+------------------------------------------------+
| Table | Key | Links to Table.Key |
+============+=======+================================================+
| gse | gse | gse_gpl.gse, gse_gsm.gse, gds.gse, sMatrix.gse |
+------------+-------+------------------------------------------------+
| gpl | gpl | gds.gpl, gse_gpl.gpl, sMatrix.gpl, gsm.gpl |
+------------+-------+------------------------------------------------+
| gsm | gsm | gse_gsm.gsm |
| gsm | gpl | gds.gpl, gse_gpl.gpl, sMatrix.gpl, gpl.gpl |
+------------+-------+------------------------------------------------+
| gds | gds | gds_subset.gds |
+------------+-------+------------------------------------------------+
| gds_subset | gds | gds.gds |
+------------+-------+------------------------------------------------+
| sMatrix | gse | gse_gpl.gse, gse_gsm.gse, gds.gse, gse.gse |
| sMatrix | gpl | gds.gpl, gse_gpl.gpl, gpl.gpl, gsm.gpl |
+------------+-------+------------------------------------------------+
| gse_gpl | gse | gse_gpl.gse, gse_gsm.gse, gds.gse, sMatrix.gse |
| gse_gpl | gpl | gds.gpl, gse_gpl.gpl, gpl.gpl, sMatrix.gpl |
+------------+-------+------------------------------------------------+
| gse_gsm | gse | gse_gpl.gse, gse.gse, gds.gse, sMatrix.gse |
| gse_gsm | gsm | gsm.gsm |
+------------+-------+------------------------------------------------+
```
Source: [Help: GEOmetadb Application, Meltzerlab/GB/CCR/NCI/NIH ©2008](http://gbnci.abcc.ncifcrf.gov/geo/geo_help.php)
## A three-table `join`
To get raw data, we need to `join` three tables with two `join` clauses. The first
`join` is a subquery in the `from` clause, using `gse_gsm` to find `gsm` records
corresponding to `gse` records. We then `join` this with `gsm` for those records.
This approach works well when you only have a few queries to make or you have
limited memory (RAM) available.
```{r, tidy=FALSE}
query<-"SELECT gsm.gsm, gsm.supplementary_file
FROM (gse JOIN gse_gsm ON gse.gse=gse_gsm.gse) j
JOIN gsm ON j.gsm=gsm.gsm
WHERE gse.pubmed_id='21743478'
LIMIT 2;"
res <- as.data.table(dbGetQuery(geo_con, query))
res[,strsplit(gsm.supplementary_file, ';\t'), by=gsm.gsm]
```
## Joins in `data.table`
We can repeat the same operation using `data.table`, once we have converted the
GEO tables to `data.table`s and set their keys. The homework assignment asks
that you try to fit the `data.table` manipulations (merge, subset, etc.) into
a single line. This approach will allow us to do additional fast joins later,
since the tables are now in memory (RAM).
```{r, tidy=FALSE}
gseDT <- data.table(dbGetQuery(geo_con, "SELECT * from gse;"), key="gse")
gsmDT <- data.table(dbGetQuery(geo_con, "SELECT * from gsm;"), key="gsm")
gse_gsmDT <- data.table(dbGetQuery(geo_con, "SELECT * from gse_gsm;"),
key=c("gse", "gsm"))
gsmDT[gse_gsmDT[gseDT[pubmed_id==21743478, gse], gsm, nomatch=0], nomatch=0][1:2,
list(gsm, supplementary_file)][,strsplit(supplementary_file, ';\t'), by=gsm]
```
## All in one line?
Can we do it all in one line of code? Yes, but it's ugly and hard to follow,
even with line-wrap. Plus, additional queries will have to reload the data from
the database. Yuk! (Don't do it this way.)
```{r, tidy=FALSE}
data.table(dbGetQuery(geo_con,
"SELECT * from gsm;"), key="gsm")[data.table(dbGetQuery(geo_con,
"SELECT * from gse_gsm;"), key=c("gse", "gsm"))[data.table(dbGetQuery(geo_con,
"SELECT * from gse;"), key="gse")[pubmed_id==21743478, gse], gsm,
nomatch=0], nomatch=0][1:2, list(gsm, supplementary_file)][,
strsplit(supplementary_file, ';\t'), by=gsm]
```
## Joining with `merge`
Some people like to use the familiar `merge`. There is a version of `merge`
built into `data.table` for improved performance. We will use the three DTs we
made previously. To remove duplicates, we use `unique`. (Why are there duplicates?)
```{r, tidy=FALSE}
unique(merge(gsmDT[,list(gsm,supplementary_file)],
merge(gseDT[pubmed_id==21743478, list(gse)],
gse_gsmDT)[,list(gsm)])[1:4, list(gsm, supplementary_file)])[,
strsplit(supplementary_file, ';\t'), by=gsm]
```
## Joining with `merge` and `magrittr`
We can also use `%>%` from `magrittr` to improve readability, again using the
three DTs we made previously. Here we will use two "lines" of code.
```{r, tidy=FALSE}
library(magrittr)
mergedDT <- unique(gseDT[pubmed_id==21743478, list(gse)] %>%
merge(y=gse_gsmDT, by=c("gse")) %>%
merge(y=gsmDT[,list(gsm,supplementary_file)], by=c("gsm")))
mergedDT[1:2, list(gsm, gse, supplementary_file)][,
strsplit(supplementary_file, ';\t'), by=gsm]
```
## Only get what you need
It makes sense to only `select` the data we need from the SQL database. Why pull
in extra data, only to ignore it? We will still use `data.table` for the `join`,
though, in keeping with the spirit of the assignment.
```{r, tidy=FALSE}
gseDT <- data.table(dbGetQuery(geo_con,
"SELECT gse from gse WHERE pubmed_id = '21743478';"), key="gse")
gsmDT <- data.table(dbGetQuery(geo_con,
"SELECT gsm, supplementary_file from gsm;"), key="gsm")
gse_gsmDT <- data.table(dbGetQuery(geo_con,
"SELECT * from gse_gsm;"), key=c("gse", "gsm"))
gsmDT[gse_gsmDT[gseDT, gsm, nomatch=0], nomatch=0][1:2,
list(gsm, supplementary_file)][,strsplit(supplementary_file, ';\t'), by=gsm]
```
## Cleanup
```{r}
dbDisconnect(geo_con)
```
## Column Name Conflicts: An Example
Let's set up an example which will lead to a column name conflict when we
do a three-table `join` in one command (line).
```{r, echo=TRUE}
suppressMessages(library(data.table))
A <- data.table(e=c(1:3), f=c(4:6), key="f")
B <- data.table(g=c(7:9), h=c(10:12), key="g")
AB <- data.table(f=c(4:5), g=c(8:9), key=c("f", "g"))
```
## Column Name Conflicts: `[` default `join`
The default `join` is a "right outer `join`". They appear to work
fine. Or do they? What's with the "f" and "g" columns in `AB[B]`?
```{r, echo=TRUE}
AB[A]
AB[B]
```
## Column Name Conflicts: `setkeyv`
We can fix the `AB[B]` output by resetting the `key` for `AB`. We reverse the
order of the key fields so that the key for B ("g") matches the first key for
AB ("g").
```{r, echo=TRUE}
setkeyv(AB, c("g", "f"))
AB[B]
```
## Column Name Conflicts: 3-table `join`
Even three-table `join`s (sort of) work, so long as we use the default `join`,
but we see that a column is renamed. "g" from table AB becomes "i.g". "f" from
table AB becomes "i.f". A's "f" gets relabled as "g". B's "g" gets relabled as
"f". In the `data.table` documentation, it says, "In all joins the names of the columns are irrelevant". And what happened to "e" and "h"?
```{r, echo=TRUE}
setkeyv(AB, c("f", "g"))
B[AB[A]]
setkeyv(AB, c("g", "f"))
A[AB[B]]
```
## Column Name Conflicts: `nomatch=0`
The problems get worse when we try to use an inner `join` (intersection). Since
"f" is in both A and AB and "g" is in both AB and B, we will have a
conflict if we try and `join` A, AB, and B in one command (line). The
result is an "empty data.table", even though the intersection should have
some rows of data.
```{r, echo=TRUE}
setkeyv(AB, c("f", "g"))
B[AB[A, nomatch=0], nomatch=0]
setkeyv(AB, c("g", "f"))
B[AB[A, nomatch=0], nomatch=0]
```
## Column Name Conflicts: `list`
In the first (most nested) `join`, A is the "i expression". If we anticipate
that "e" and "f" from A will be renamed "i.e" and "i.f" during the `join`,
then we can list them as such and avoid the "empty data.table" problem.
```{r, echo=TRUE}
setkeyv(AB, c("f", "g"))
B[AB[A, list(g, i.e, i.f), nomatch=0], list(i.e, i.f, g, h), nomatch=0]
```
## Column Name Conflicts: `merge`
Using `merge`, we don't encounter these troubles. We can get the same
"inner join" result without the renaming of columns and the need for explicit
"j expression" column lists. We just need to use `by=` in the
outer-nested `merge`.
```{r, echo=TRUE}
merge(B, merge(AB, A), by="g")
```
## Column Name Conflicts: `magrittr`
Here is the same example using `%>%` pipes from `magrittr`.
```{r, echo=TRUE}
suppressMessages(library(magrittr))
merge(x=AB, y=A, by="f") %>% merge(y=B, by="g")
```
Or simply (but less explicitly)...
```{r, echo=TRUE}
merge(AB, A) %>% merge(B, by="g")
```
## Column Name Conflicts: `plyr`
We can also `join` with `plyr`, simply *and* explicitly.
```{r, echo=TRUE}
suppressMessages(library(plyr))
join(AB, A, type="inner") %>% join(B, type="inner")
```
## Column Name Conflicts: `plyr` left `join`
In this *particular* case, we would get the same result using the default
left `join`, but that would not always be true in *every* case. It works here
because the left-hand table of each `join` contains only those rows we would
want in the final result. (Try reversing the positions of A and AB and see the difference for yourself.)
```{r, echo=TRUE}
join(AB, A) %>% join(B)
```