-
Notifications
You must be signed in to change notification settings - Fork 4
/
block_2_session_2_programming_w_data.qmd
611 lines (318 loc) · 9.58 KB
/
block_2_session_2_programming_w_data.qmd
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
---
title: "Hacking for Science"
subtitle: "Block 2, Session 2: Programming with Data"
author: "Matt Bannert"
format: revealjs
chalkboard: true
echo: true
footer: "Hacking for Science by Dr. Matthias Bannert is licensed under [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/?ref=chooser-v1)"
---
# Data Generating Processes in Science
## Simulation
:::: {.columns}
::: {.column width="40%" }
### Why
- Analyzing Complex Systems
- Demos
- Proposals / Grants
- reproducible examples, [reprex R package](https://reprex.tidyverse.org/)
:::
::: {.column width="60%" }
### Process
```{r}
set.seed(123)
rnorm(3)
set.seed(1)
rnorm(3)
set.seed(123)
rnorm(3)
```
:::
::::
## Logging / Tracking
:::: {.columns}
::: {.column width="40%" }
### Process
- webservers
- mobile phones
- IoT devices
- tracking tools, e.g., Google Analytics
:::
::: {.column width="60%" }
### Form of Resulting Data
- text files
- granular
- event based
- biased (tracking)
:::
::::
## Surveys
:::: {.columns}
::: {.column width="40%" }
### Types
- multi mode surveys (paper / online forms)
- Recordings
:::
::: {.column width="60%" }
### Form of Resulting Data
- rectangular data (1-line-1-observation)
- text
- cross sectional
- longitudinal data
:::
::::
## APIs & Web Scraping
:::: {.columns}
::: {.column width="40%" }
### Process
- Automated, regular updates
- Transformation of structured data into analysis friendly datasets (regular expressions, DOM extraction)
:::
::: {.column width="60%" }
### Form of Resulting Data
- text strings
- nested data
- standardized data
:::
::::
## What DGPs Have You Worked With? What DGPs Do You Expect to Face in Your Work? {.center}
# Representing Data
## Data Management: Memory, Files, Databases {.center}
## In Memory
- vector
- matrix
- data.frame / data.table / tibble
- list
- environment
## On Disk
- .RData
- .parquet
- feather
- .xlsx
- .csv
- .json
- .xml
see also: [RSE Book on Data Management](https://rse-book.github.io/data-management.html)
## In a Database
- interface
- query language, e.g., SQL
## Types of Data: Time Series
<style>
.smaller {
font-size: .55em
}
</style>
:::: {.columns}
::: {.column width="60%" }
```{r, message=FALSE, warning=FALSE, fig.height=4}
library(kofdata)
library(tstools)
tsl <- window(get_time_series("ch.kof.barometer"))
tsplot("KOF Barometer" =
window(tsl$ch.kof.barometer,
start = c(2010,1))
)
```
:::
::: {.column width="40%" .smaller}
**in memory**
- ts
- xts
- tsibble
- zoo
> (!) Try out the `tsbox` R package to easily switch from one representation
to another.
**on disk**
- [.csv](https://github.com/swissdata/demo) (long format, wide format)
- [.xml](https://www.nsdp.admin.ch/variable/72.xml)
- .json
- .RData
:::
::::
## Types of Data: Rectangular Datasets {.center}
## Cross Sectional Data
```{r}
head(mtcars)
```
- multiple variables
- one period
## Panel Data
- multiple variables
- longitudinal
- e.g., German Socio Economic Panel (GSOEP)
## Types of Data: Nested Data
:::: {.columns}
::: {.column width="60%" }
```{r}
l <- list()
l$element1 <- 2
l$element2 <- head(mtcars[,1:3],4)
l
```
:::
::: {.column width="40%" }
examples:
- [meta information](https://github.com/swissdata/demo), sector classification (hierarchical), GDP components, translations, attributes, properties,
- [Geo spatial data](https://github.com/mbannert/maps/blob/master/ch_bfs_regions.geojson)
:::
::::
## Hands on: [Block 2, Task 2 -- Trying out different representations](https://github.com/h4sci/h4sci-tasks/issues/6) {.center}
# R Three Ecosystems to Manipulate Data
## Base R
:::: {.columns}
::: {.column width="40%" }
- vectors, matrices, data.frames
- no extensions needed
- much better than its marketing
- split, apply, combine approach
:::
::: {.column width="60%" }
```{r}
by_cyl <- split(mtcars, mtcars$cyl)
out <- lapply(by_cyl,
function(x) summary(
lm(mpg~.,data = x)
)
)
str(out, max.level = 1)
```
:::
::::
## data.table
- [CRAN package](https://cran.r-project.org/web/packages/data.table/index.html)
- written by Matt Dowle et al.
- fastest ecosystem, including fwrite/fread for fast disk i/o
```{r, message=FALSE,warning=FALSE, }
library(data.table)
dt <- fread("../data/simulated_survey.csv")
head(dt)
```
## data.table c'd
```{r, message=FALSE,warning=FALSE, eval=FALSE}
# i, j, by
dt[, obs_avg := rowMeans(.SD), .SDcols = c("basic", "advanced", "structure")]
head(dt)
```
- SQL reminiscent concept and syntax
- works with pointers / reference -> it changes objects in place
## tidyverse
- dplyr, tibble, ....
- [best documentation](https://www.tidyverse.org/)
- fast
- uses references, too
- very popular for interactive use
- pipe operator: %>% (base R got a pipe in the meantime, too)
- pretty printing
## tidyverse
```{r, message=FALSE,warning=FALSE}
library(dplyr)
mtcars %>%
filter(cyl > 4) %>%
nrow()
```
## Block 2, Task 3: [Three R Ecosystems to Manipulate Data](https://github.com/h4sci/h4sci-tasks/issues/7) {.center}
# Databases (DBMS)
## When to Use a Database ? {.center}
## Passive Use
- direct access
- no API
- flexible queries needed
## Active Use (in the sense of setting it up, running it)
- as a backend, e.g., survey (transactional database)
- in research projects when you want to share data inside your lab
- when you need to restrict access at different levels
## Active Use c'd
- to expose data through an API (to external collaborators or the public)
- need to [integrate with different systems / tools and programming languages](https://github.com/mbannert/timeseriesdb/blob/ca3939a5686f0e68bc3d5cb828d0891795a4eac3/inst/sql/create_functions_collections.sql#L63)
- specific operations, e.g., spatial data
## Which DBMS Should I Use ? {.center}
## Which DBMS Should I Use ?
1. **relational** DBMS should be the **default choice**, don't believe me? Believe [him](https://blog.jooq.org/tag/mongodb/). Note, you can use json inside SQL DBs
as well.
## Which DBMS Should I Use ?
2. Which **relational** DBMS should I Use?
- SQLite is for prototypes and mobile phones
- MySQL is for kids
- PostgreSQL, MS SQL and Oracle are at the same level for many science
applications
## Can You Explain 'Relational'
![](img/timeseriesdb_1_0.png)
## Are There Any Disadvantages of Databases?
- You have to maintain them, even if you don't need them
- more setup overhead: dev and production system(s) needed
- solid, free solutions are only temporal
- you need an interface for collaborators who don't speak SQL
- some really, really, really big datasets may ask for specific methods
# Getting Started with Relational Databases (RDBMS)
## Hosting
- localhost (dev only)
- docker environment
- university VM
- homeserver
- cloud (either VM and install on your own, or DB specific Cloud)
## Client
- install drivers locally at OS level
- install client library (R packages are usually wrappers around C interfaces)
## Design
- integrity (think primary key, foreign key for starters)
- Draw up a design... [dbdiagram.io](https://dbdiagram.io/) is a fun tool,
paper & pencil also work pretty well
## Start Simple, Catch a Breath of SQL Air with SQLite
```{r}
library(RSQLite)
db_path = "../data/h4sci.sqlite3"
con <- dbConnect(RSQLite::SQLite(), db_path)
dbWriteTable(con, dbQuoteIdentifier(con,"mtcars"), mtcars, overwrite = T)
dbWriteTable(con, dbQuoteIdentifier(con,"flowers"), iris, overwrite = T)
dbGetQuery(con, "SELECT * FROM flowers LIMIT 3")
```
Note: Foreign Key Handling is [very limited in SQLite](https://stackoverflow.com/questions/1884818/how-do-i-add-a-foreign-key-to-an-existing-sqlite-table).
## Example Query
```{r}
dbGetQuery(con, "SELECT * FROM mtcars WHERE mpg > 30")
```
## Database Access
```{r,eval=FALSE}
library(RSQLite)
db_path = "../data/h4sci.sqlite3"
con <- dbConnect(RSQLite::SQLite(),
db_path)
```
```{r, eval=FALSE}
library(RPostgres)
con <- dbConnect(drv = Postgres(),
dbname = "postgres",
user = "postgres",
host = "some.server.or.ip",
password = .rs.askForPassword(
"enter your pw"
)
)
```
- Essentially the same interface (DBI)
- server, files are abstracted away
- host, password, port etc. needed for Postgres
## Basic SQL Syntax
```sql
SELECT * FROM schema.table;
INSERT INTO schema.table VALUES ('abc',2,3);
SELECT name, salary FROM staff
WHERE position = 'manager'
ORDER BY salary DESC;
```
- '*' SELECTs all data from a given table
- INSERTs values to a table while checking integrity (data types)
- SELECTs name and salary from table staff for all managers and
orders the output by salary from highest to lowest
## Further Reads
- [SQLite Tutorial](https://www.sqlitetutorial.net/)
- [PostgreSQL 15 Documentation](https://www.postgresql.org/docs/12/index.html) (Jump in at 'table basics')
- [Vignettes of the {dm} package](https://cran.r-project.org/web/packages/dm/index.html), in particular the [data.frame to dm part](https://cran.r-project.org/web/packages/dm/vignettes/howto-dm-df.html)
## Hands on: Block 2, Task 4: [A Little SQL](https://github.com/h4sci/h4sci-tasks/issues/8) {.center}
## How to Work with an Application Programming Interface (API)
1. RTFM
2. Experiment 'per pedes'
3. Write a Wrapper if it does not exist
4. Use the Wrapper
Here is [an R example](https://github.com/h4sci/h4sci-tasks/blob/main/demo/met_api.R) to get `r emojifont::emoji("umbrella") ` images from the
MET collection.