forked from anabento/R_Bootcamp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathM4Functions.Rmd
More file actions
236 lines (158 loc) · 5.01 KB
/
M4Functions.Rmd
File metadata and controls
236 lines (158 loc) · 5.01 KB
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
---
title: ""
author: ""
date: ""
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval=FALSE)
```
#<span style="color:cadetblue">Functions</span>
This module will cover:
- function syntax
- control statements
- logic statements
which will require the following skills already covered:
- data structure
- assigning an object
***
##<span style="color:cadetblue">What is a function</span>
Functions incorporate sets of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a script and called when needed.

You can write your own functions, but `R` and its packages come with "pre-made" functions as well.
A useful function is ```rm(list=ls())```, which clears `R`’s brain.
Others include seq(), log(), sin()...
A typical function has the follwoing architecture
```{r function, eval=FALSE}
func.name = function (arglist) {body}
```
###<span style="color:orangered">**Let's copy and paste them into the console**:</span>
##<span style="color:cadetblue">Example 1a:</span> Simple function
```{r function1}
my.function1<-function(a,b,c){
tmp<-a+b
tmp2<-tmp/c
return(tmp2)
}
#Using this function we have:
out1<-my.function1(4,7,2)
out1
```
###<span style="color:orangered">**Practice**:</span> Choose other sets of numbers
```{r function2}
out2<-my.function1(,,)
out2
```
###<span style="color:orangered">**Practice**:</span> Create a function that will return the sum of 2 integers
```{r function15}
```
##<span style="color:cadetblue">Example 1b:</span> Rounding function
```{r function13}
Roundme <- function(x){
#this function uses the floor function to
#do what the round function does
x <- x+0.5
floor(x)
}
```
##<span style="color:cadetblue">Example 2a:</span> Control statements **if**
```{r function11}
x <- 8
if (x < 9) print("x is less than nine")
x <- 10
if (x < 9) print("x is less than nine")
```
##<span style="color:cadetblue">Example 2b:</span> Control statements **if else**
```{r function3}
a<-5
if(a<1){
b<-5
c<-4
} else {
b<-10
}
b
```
###<span style="color:orangered">**Practice**:</span> Uncomment and fill in a simple function with a nested if statement will print alternative outcomes
```{r function14}
#Isit <- function(x){
# if (x == ??)
#print("???!")
#else print("???")
#}
#Isit(?)
#Isit(?)
```
##<span style="color:cadetblue">Example 2c:</span> Control statements **while**
```{r function10}
x <- 2
while(x < 10){
print(x)
x <- x+1
}
print("The end")
```
##<span style="color:cadetblue">Example 3a:</span> **for** loop
```{r function4}
a<-c() # creating an empty vector
for(i in 1:10){ # i becomes 1 through 10 iteratively
a[i]<-i^3 # this is the operation
}
a # seeing what the vector a becomes
```
##<span style="color:cadetblue">Example 4:</span> Random number generation
Here is an example, there are a number of distributions available
```{r function5}
random_numbers<-rnorm(3,mean=5,sd=3) # normal distribution generates 3 numbers with a mean and a sd
random_numbers
```
##<span style="color:cadetblue">Example 5:</span> Descriptive stats
```{r function6}
dat<-rnorm(30,mean=5,sd=3) # creating a vector
dat # check it
sort (dat) #sort vector
unique (dat) #unique values
max(dat) #max
min(dat) #min
mean(dat) # taking the mean
sum(dat) # sum the vector elements
var(dat) # taking the variance
length(dat) # length of vector
sqrt(var(dat)/length(dat)) # standard error
```
###<span style="color:orangered">**Practice**:</span> Write a function to compute standard error of dat
```{r function12}
```
##<span style="color:cadetblue">Example 6:</span> The apply function
```apply``` are functions to manipulate slices of data from matrices, arrays, lists and dataframes in a repetitive way
```{r function7}
X <- matrix(rnorm(30), nrow=5, ncol=6) # creating a matrix
# Sum the values of each column with `apply()`
apply(X, 2, sum)
```
###<span style="color:orangered">**Practice**:</span> How do you calculate the sum of each row using apply?
##<span style="color:cadetblue">Example 7:</span> The lapply function
```lapply``` applies a given function to every element of a list and obtain a list as result
```{r function8}
# create a list with 2 elements
l <- list(a = 1:10, b = 11:20)
# the mean of the values in each element
lapply(l, mean)
# the sum of the values in each element
lapply(l, sum)
```
##<span style="color:cadetblue">Example 8:</span> The sapply function
```sapply``` will return either a vector, with elements [[‘a’]] and [[‘b’]], or a matrix with column names “a” and “b”
```{r function9}
# create a list with 2 elements
l <- list(a = 1:10, b = 11:20)
# mean of values using sapply
l.mean <- sapply(l, mean)
# what type of object was returned?
class(l.mean)
# it's a numeric vector, so we can get element "a" like this
l.mean[['a']]
```
## <span style="color:cadetblue">Going further</span>
rapply, tapply, parallel computing in R (https://www.r-bloggers.com/how-to-go-parallel-in-r-basics-tips/)