This repository has been archived by the owner on Jan 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
01_Rintro.Rmd
320 lines (229 loc) · 6.46 KB
/
01_Rintro.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
---
title: "Introduction to R"
---
```{r, echo=FALSE, message=FALSE, results='hide', purl=FALSE}
source("knitr_header.R")
```
# Logistics
[<i class="fas fa-desktop fa-3x" aria-hidden="true"></i> Presentation](presentations/PS_01_intro.html){target="_blank"}
[<i class="fa fa-file-code-o fa-3x" aria-hidden="true"></i> R Script](`r output`){target="_blank"} Download this file and open it (or copy-paste into a new script) with RStudio so you can follow along.
# First Steps
## Variables
```{r}
x=1
x
```
We can also assign a vector to a variable:
```{r}
x=c(5,8,14,91,3,36,14,30)
x
```
And do simple arithmetic:
```{r}
x+2
```
<div class="well">
Create a new variable called `y` and set it to `15`
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo1">Show Solution</button>
<div id="demo1" class="collapse">
```{r, purl=F}
y=15
```
</div>
</div>
Note that `R` is case sensitive, if you ask for `X` instead of `x`, you will get an error
```{r,eval=FALSE}
X
Error: object 'X' not found
```
### Variable naming conventions
Naming your variables is your business, but there are [5 conventions](http://www.r-bloggers.com/consistent-naming-conventions-in-r/) to be aware of:
* **alllowercase**: _e.g._ `adjustcolor`
* **period.separated**: _e.g._ `plot.new`
* **underscore_separated**: _e.g._ `numeric_version`
* **lowerCamelCase**: _e.g._ `addTaskCallback`
* **UpperCamelCase**: _e.g._ `SignatureMethod`
# Subsetting
```{r}
x
```
Subset the vector using `x[ ]` notation
```{r}
x[5]
```
You can use a `:` to quickly generate a sequence:
```{r}
1:5
```
and use that to subset as well:
```{r}
x[1:5]
```
# Using Functions
To calculate the mean, you could do it _manually_ like this
```{r}
(5+8+14+91+3+36+14+30)/8
```
Or use a function:
```{r}
mean(x)
```
Type `?functionname` to get the documentation (`?mean`) or `??"search parameters` (??"standard deviation") to search the documentation. In RStudio, you can also search in the help panel. `mean` has other arguments too:
`mean(x, trim = 0, na.rm = FALSE, ...)`
In RStudio, if you press `TAB` after a function name (such as `mean( `), it will show function arguments.
![Autocomplete screenshot][pic1]
[pic1]: img/autocomplete.png "Autocomplete Screenshot"
<div class="well">
Calculate the standard deviation of `c(3,6,12,89)`.
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo2">Show Solution</button>
<div id="demo2" class="collapse">
```{r, purl=F}
y=c(3,6,12,89)
sqrt((sum((y-mean(y))^2))/(length(y)-1))
#or
sd(y)
#or
sd(c(3,6,12,89))
```
</div>
</div>
Writing functions in R is pretty easy. Let's create one to calculate the mean of a vector by getting the sum and length. First think about how to break it down into parts:
```{r}
x1= sum(x)
x2=length(x)
x1/x2
```
Then put it all back together and create a new function called `mymean`:
```{r}
mymean=function(f){
sum(f)/length(f)
}
mymean(f=x)
```
Confirm it works:
```{r}
mean(x)
```
<div class="well"> Any potential problems with the `mymean` function? </div>
# Missing data: dealing with `NA` values
```{r}
x3=c(5,8,NA,91,3,NA,14,30,100)
```
<div class="well">" What do you think `mymean(x3)` will return? </div>
Calculate the mean using the new function
```{r}
mymean(x3)
```
Use the built-in function (with and without na.rm=T)
```{r}
mean(x3)
mean(x3,na.rm=T)
```
Writing simple functions is easy, writing robust, reliable functions can be hard...
## Logical values
R also has standard conditional tests to generate `TRUE` or `FALSE` values (which also behave as `0`s and `1`s. These are often useful for filtering data (e.g. identify all values greater than 5). The logical operators are `<`, `<=`, `>`, `>=`, `==` for exact equality and `!=` for inequality.
```{r}
x
x3 > 75
x3 == 40
x3 > 15
```
And you can perform operations on those results:
```{r}
sum(x3>15,na.rm=T)
```
or save the results as variables:
```{r}
result = x3 > 3
result
```
<div class="well">
Define a function that counts how many values in a vector are less than or equal (`<=`) to 12.
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo3">Show Solution</button>
<div id="demo3" class="collapse">
```{r, purl=F}
mycount=function(x){
sum(x<=12)
}
```
Try it:
```{r}
x3
mycount(x3)
```
oops!
```{r, purl=F}
mycount=function(x){
sum(x<=12,na.rm=T)
}
```
Try it:
```{r}
x3
mycount(x3)
```
Nice!
</div>
</div>
# Generating Data
There are many ways to generate data in R such as sequences:
```{r}
seq(from=0, to=1, by=0.25)
```
and random numbers that follow a statistical distribution (such as the normal):
```{r}
a=rnorm(100,mean=0,sd=10)
```
Let's visualize those values in a histogram:
```{r,fig.height=3}
hist(a)
```
We'll cover much more sophisticated graphics later...
# Data Types
## Matrices
You can also use matrices (2-dimensional arrays of numbers):
```{r}
y=matrix(1:9,ncol=3)
y
```
Matrices behave much like vectors:
```{r}
y+2
```
and have 2-dimensional indexing:
```{r}
y[2,3]
```
<div class="well">
Create a 3x3 matrix full of random numbers. Hint: `rnorm(5)` will generate 5 random numbers
<button data-toggle="collapse" class="btn btn-primary btn-sm round" data-target="#demo4">Show Solution</button>
<div id="demo4" class="collapse">
```{r, purl=F}
matrix(rnorm(9),nrow=3)
```
</div>
</div>
## Data Frames
Data frames are similar to matrices, but more flexible. Matrices must be all the same type (e.g. all numbers), while a data frame can include multiple data types (e.g. text, factors, numbers). Dataframes are commonly used when doing statistical modeling in R.
```{r}
data = data.frame( x = c(11,12,14),
y = c("a","b","b"),
z = c(T,F,T))
data
```
You can subset in several ways
```{r}
mean(data$x)
mean(data[["x"]])
mean(data[,1])
```
# Loading Packages
For installed packages: `library(packagename)`.
New packages: `install.packages()` or use the package manager.
```{r message=F,warning=FALSE}
library(ggplot2)
```
> R may ask you to choose a CRAN mirror. CRAN is the distributed network of servers that provides access to R's software. It doesn't really matter which you chose, but closer ones are likely to be faster. From RStudio, you can select the mirror under Tools→Options or just wait until it asks you.
If you don't have the packages above, install them in the package manager or by running `install.packages("raster")`.
# Today's task
Now [complete the first task here](CS_01.html) by yourself or in small groups.