-
Notifications
You must be signed in to change notification settings - Fork 2
/
worksheet.R
136 lines (101 loc) · 2.33 KB
/
worksheet.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
# Worksheet for SQLite lesson
# First you will need to copy the portal.sqlite file
# to your own workspace so that your changes to the file
# will not affect everyone else in the class!
file.copy('data/portal.sqlite', 'myportal.sqlite')
library(RSQLite)
# Create a connection object
con <- ...(RSQLite::SQLite(), "myportal.sqlite")
# Read a table
library(dplyr)
species <- ...(con, 'species')
# Upload a new table
df <- data.frame(
id = c(1, 2),
name = c('Alice', 'Bob')
)
...(con, 'observers', df)
# remove existing observers table
dbRemoveTable(con, 'observers')
# Recreate observers table
...(con, 'observers', list(
id = '...',
name = 'text'
))
# add data to observers table
# with auto-generated id
df <- data.frame(
name = c('Alice', 'Bob')
)
...(con, 'observers', df, append = TRUE)
# Try adding a new observer with existing id
df <- data.frame(
id = c(1),
name = c('J. Doe')
)
...(con, 'observers', df,
append = TRUE)
# Try violating foreign key constraint
dbExecute(con, 'PRAGMA foreign_keys = ON;')
df <- data.frame(
month = 7,
day = 16,
year = 1977,
plot_id = '...'
)
dbWriteTable(con, 'surveys', df,
append = TRUE)
# Queries
# basic queries
...(con, "... year ... surveys")
dbGetQuery(con, "SELECT ... FROM ...")
dbGetQuery(con, "...
FROM surveys")
# limit query response
dbGetQuery(con, "SELECT year, species_id
FROM surveys
...")
# get only unique values
dbGetQuery(con, "SELECT ... species_id
FROM surveys")
dbGetQuery(con, "SELECT ...
FROM surveys")
# perform calculations
dbGetQuery(con, "SELECT plot_id, species_id,
sex, ...
FROM surveys")
dbGetQuery(con, "SELECT plot_id, species_id, sex,
weight / 1000 ...
FROM surveys")
dbGetQuery(con, "SELECT plot_id, species_id, sex,
...
FROM surveys")
# filtering
# hint: use alternating single or double quotes to
# include a character string within another
dbGetQuery(con, "SELECT *
FROM surveys
... species_id ...")
dbGetQuery(con, "SELECT *
FROM surveys
... year ...")
dbGetQuery(con, "SELECT *
FROM surveys
... year ... species_id ...")
dbGetQuery(con, "SELECT *
FROM surveys
WHERE ...
... species_id = 'DM'")
# Joins
# one to many
dbGetQuery(con, "SELECT weight, plot_type
FROM surveys
...
... = ...")
# many to many
dbGetQuery(con, "SELECT weight, genus, plot_type
FROM surveys
... plots
ON ...
... species
ON ...")