-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBio110 - Week 1 Lab.Rmd
238 lines (139 loc) · 8.82 KB
/
Bio110 - Week 1 Lab.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
---
title: "Bio 110 Heart Rate lab"
output:
pdf_document: default
html_notebook: default
---
# Lab 1 - Heart Rate Lab
Before getting started with the Heart Rate Lab, we'll go over some basics of using R and this R Notebook. For a more in depth dive, check out this resource on Coding Club:
https://ourcodingclub.github.io/2016/11/13/intro-to-r.html
As you go through this document, you'll encounter a series of grey areas with little green "play" buttons in the upper right-hand corner. These are called code chunks. This is where you can write and run R code. Some of the code chunks already have example code, while some are intended for you to write and run your own code. To run the code chunk, just click the play button. The results will appear below the code chunk.
## Coding with R
### Comments
One of the most important things you can do with any scripting language is to add comments to your code. Comments are basically instructions or descriptions you insert in your code that aren't executed as code. They're sometimes referred to as "love letters to your future self".
In R, a comment is preceded by a hash mark (#):
```{r}
# This is a comment. Use it to explain what's going on!
```
You don't have to comment every single command, but it's often a good idea to add enough comments so your future self (or collaborator) will understand your code.
### Assigning variables
One of the most common things to do in any scripting language is to create a variable and set it equal to something. In R, you use the "<-" (left-pointing arrow) to assign a value to a variable. The value can be an integer, text string, expression (e.g. "2+2"), or output of a function. Take a look at the example below:
```{r}
# assign a value to a:
a<-"my value for a"
# assign a value to myFavoriteNumber:
myFavoriteNumber<-27
# print a and myFavoriteNumber
a
myFavoriteNumber
```
Note in the above examples that quotation marks are used to define a, but not myFavoriteNumber. This is because variables can have different types, and quotes (or lack of quotes) can help indicate what kind of type your variable is. Generally quotes are required for a string (e.g. text) variables, while quotes are not required for integers, functions, or setting one variable equal to another.
Now it's your turn. In the code block below, set a variable "myVar" equal to five times 20, and then print it:
```{r}
#enter your code here
```
### Functions
Functions are basically shortcut commands that perform a certain task. Functions usually take input values (often called "arguments"), and return some output. Let's take a look below at the "sqrt" function:
```{r}
# sets "value" equal to the sqaure root of 20
value<-sqrt(20)
value
```
One of the great things about RStudio is that you can quickly access documentation on functions by using the "help" function. Running this function will display documentation in the lower right-hand window:
```{r}
help(sqrt)
```
Notice in the "Arguments" section, "x" is labled as "a numeric or complex vector or array". Take a look at this example:
```{r}
sqrt(9)
#explicitly defining arguments:
sqrt(x=9)
#this won't work:
sqrt(y=9)
```
Why does the "x" work, but not the "y"? Because the documentation on sqrt defines the argument as "x".
Now it's your turn. Use help to look up the "plot" function.
```{r}
#enter and run your "help" code here
```
Notice that the Arguments section for plot is much more complex than that for sqrt. A plot requires x and y arguments (or values). Additionally, there are several more arguments that can be used to specify the type of plot, titles, labels, etc. Click on "graphical parameters"
to see a list of more arguments that can be used to customize a plot.
Now use the plot function, and explicitly label the x value 20, and the y value 30.
```{r}
#enter and run your "plot" code here
```
### Vectors
Vectors are a type of data structure in R, usually referring to an array of values. A vector is often a list of values in a column of data from a spreadsheet. To create a vector, you use the "c" function:
```{r}
myFirstVector<-c(1,2,3,4,5)
#print myFirstVector
myFirstVector
```
Now it's your turn. Create a vector named "vector", and have it contain the values 30, 20, 40, 15, and 50.
```{r}
#enter your code here
```
### Plotting Heart Rate
Now let's apply some of these concepts and functions above to plot heart rate. We wish to create a simple scatterplot with continuous x and y variables, find the best-fit line, and determine the values for the slope and y-intercept.
```{r}
#start by entering a vector of the x-values in the parentheses below, time in seconds
x<-c(0, 20, 40, 60, 80, 100, 120)
#and one for the y-values, heartbeats (enter your data in the parentheses in order)
y1<-c(0, )
#then plot y against x to see a scatterplot of your data
#the operator "~" means "value on the left depends upon value on the right"... or "y1 is a function of x":
plot(y1~x)
```
We can add additional information to the plot, including specific x and y axis limits, axes labels, and a title.
```{r}
#if you want to adjust the axis limits (adjust as needed for your data), add labels, and a title
plot(y1~x, xlim=c(0,120), ylim=c(0,140), main="My Title", xlab="time in seconds", ylab = "number of heartbeats")
```
Now you should have a scatterplot of your heartbeat data with some labels. Please ask for help from your instructor or TA if you are having any issues so far.
Next we want to add a best fit trendline to determine heartrate.
```{r}
# in order to run the abline function below, you must first run the plot function:
plot(y1~x, xlim=c(0,120), ylim=c(0,140), main="My Title", xlab="time in seconds", ylab = "number of heartbeats")
#to add the line, setting the y intersect at zero, and get its slope, fit a linear model to the data and store the results in a variable (named "model" here).
model<-lm(formula=y1~0+x)
#add a best-fit line to the graph
abline (reg=model)
#type the name of the variable to see values of the slope and y-intercept
model
```
Click on the plot to see a scatter plot with a best fit line for your resting heartrate. Click on R Console to see the coefficient which is the slope of the line and reflects your resting heartrate in heartbeats per second.
To compare your resting heartrate to your heartrate under your experimental condition, make a vector called y2 with the heartbeat data from your experimental condition.
```{r}
#enter the heartbeat data collected for your experimental condition in the parentheses
y2<-c(0, )
```
Now we can use the "matplot" function to plot multiple columns or sets of data:
```{r}
matplot(x=x, y=cbind(y1,y2), type="p", col=c("red", "green"), pch=c(16,16), main="Mt Title", xlab="time in seconds", ylab="heartbeats")
```
The scatterplot above should show both sets of data in a scatterplot. Follow the instructions below to add trendlines and calculate the slopes of those lines.
```{r}
#prior to generating the plot, you can set some graphical parameters with the "par" function
#ces.axis changes the font size on the axis values (0.75 is 75% of default). Adjust this as necessary to make sure all x and y axis
par(cex.axis=0.6)
#more on graphical parameters here: https://www.rdocumentation.org/packages/graphics/versions/3.6.2/topics/par
matplot(x=x, y=cbind(y1,y2), type="p", col=c("red", "green"), pch=c(16,16), main="My Title", xlab="time in seconds", ylab="heartbeats", ylim=c(0,140))
#note: you may have to adjust the ylim values to ensure all your data displays - for example, if you have a data point at 150, you'll want to increase your ylim 2nd value so it's 150 or greater
#repeat the linear model for y1
model<-lm(y1~0+x)
#plot its line in red
abline (model, col="red")
#and now the model for y2
model2<-lm(y2~0+x)
#and a green line for it
abline(model2, col="green")
#and to get the new slope and intercept
model2
#to add a legend, first need coordinates of the legend, c(“labels”), lty determines symbols with 1 = lines, lwd determines width of lines, colors
legend(x=0, y=140, legend=c("experimental heartrate", "control heartrate"), lty=c(1,1), lwd=c(2.5, 2.5), col=c("green", "red") )
#note - you may have to adjust the x and y values of the legend if they don't fit in the plot.
```
Finally, you'll need to turn in a copy of the last plot. There are two ways to do this:
1) copy the entire code chunk above (not including the "```" parts), and paste in the console prompt in the window below. This should generate the plot in the "Plots" tab on the right. From there you can click "Export", then "save image as...", and save the image to your computer.
2) Hover your mouse over the plot above, and control-click (e.g. "right click"), and then select "save as...", and save the image to your computer.
Then email it to your professor. The file name should be in this format: "MyName_Lab1.jpg". So if your name is Jane Doe, the file name should be "JaneDoe_Lab1.jpg".