forked from rdpeng/RepData_PeerAssessment1
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPA1_template.Rmd
253 lines (164 loc) · 6.94 KB
/
PA1_template.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
---
title: "Reproducible Research: Peer Assessment 1"
output:
rmarkdown::html_document:
theme: flatly
keep_md: true
---
## Loading and preprocessing the data
```{r setup, results='hide'}
# Disable scientific notation
options(scipen = 1)
# Load libraries
library(tidyverse)
# Load data
if(!file.exists("activity.csv")) {
unzip("activity.zip")
}
activity <- read_csv("activity.csv")
```
## What is mean total number of steps taken per day?
*Calculate the total number of steps taken per day.*
```{r Q1.1}
activity.daily <- group_by(activity, date) %>%
summarize(steps = sum(steps))
```
*Histogram of steps per day.*
```{r Q1.2}
ggplot(activity.daily, aes(steps)) +
geom_histogram(binwidth = 2000) +
labs(title = "Histogram of Daily Steps",
x = "Daily Steps",
y = "Count") +
theme_light()
```
*Calculate mean and median of the total number of steps taken per day.*
```{r Q1.3}
daily.steps.mean <- mean(activity.daily$steps, na.rm = T)
daily.steps.median <- median(activity.daily$steps, na.rm = T)
```
- Mean of total number of steps taken per day: `r round(daily.steps.mean, 2)`
- Median of the total number of steps taken per day: `r daily.steps.median`
## What is the average daily activity pattern?
*Make a time series plot (i.e. type="l") of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all days (y-axis).*
```{r Q2.1}
activity.interval <- group_by(activity, interval) %>%
summarize(avg.steps = mean(steps, na.rm = T))
ggplot(activity.interval, aes(interval, avg.steps)) +
geom_line() +
labs(title = "Daily Average Number of Steps",
x = "5-Minute Interval",
y = "Average Number of Steps") +
theme_light()
```
*Which 5-minute interval, on average across all the days in the dataset, contains the maximum number of steps?*
```{r Q2.2}
knitr::kable(top_n(activity.interval, 1, avg.steps))
```
## Imputing missing values
*Calculate total number of rows with NAs.*
```{r Q3.1}
summary(activity$steps)["NA's"]
```
*Devise a strategy for filling in all of the missing values in the dataset.*
```{r Q3.2}
# Impute NA as average between interval step counts
activity <- mutate(activity, steps.imputed = NA) %>%
select(steps, steps.imputed, date, interval)
for (i in 1:nrow(activity)) {
# Identify rows with NA
if(is.na(activity$steps[i])) {
# Get previous step count
# If no previous value exists (i.e. row 1), default to zero steps
previous.row <- (i - 1)
previous.steps <- ifelse(previous.row < 1, 0,
activity$steps.imputed[previous.row])
# Get next step count
# If no next value exists (i.e beyond last row), default to previous steps
next.row <- i + 1
while(is.na(activity$steps[next.row] & next.row <= nrow(activity))) {
next.row = next.row + 1
}
next.steps <- ifelse(next.row > nrow(activity),
previous.steps,
activity$steps[next.row])
# Impute NA as average between values
imputed.steps <- mean(c(previous.steps, next.steps))
activity$steps.imputed[i] <- imputed.steps
} else { activity$steps.imputed[i] <- activity$steps[i] }
}
rm(list = c("i",
"imputed.steps",
"next.row",
"next.steps",
"previous.row",
"previous.steps"))
```
*Create a new dataset that is equal to the original dataset but with the missing data filled in.*
```{r Q3.3}
activity.imputed <- select(activity, steps.imputed, date, interval) %>%
rename(steps = steps.imputed)
```
*Make a histogram of the total number of steps taken each day. Calculate and report the mean and median total number of steps taken per day. Do these values differ from the estimates from the first part of the assignment? What is the impact of imputing missing data on the estimates of the total daily number of steps?*
```{r Q3.4, fig.width=10}
# Prepare daily data for histogram comparing original and imputed data
activity.daily.imputed <- group_by(activity.imputed, date) %>%
summarize(steps = sum(steps))
# Join daily average data frames with original and imputed data
activity.daily.long <- full_join(activity.daily,
activity.daily.imputed,
by = c("date" = "date")) %>%
rename(original = steps.x, imputed = steps.y) %>%
gather(data, steps, -date) %>%
mutate(data = factor(data, levels = c("original", "imputed")))
# Create histogram with facets
ggplot(activity.daily.long, aes(steps, fill = data)) +
geom_histogram(binwidth = 2000) +
geom_density(alpha = 0, aes(y = ..scaled.. * 12),
adjust = 1.5,
color = "blue",
size = 0.5) +
geom_vline(aes(xintercept = mean(steps, na.rm = T)),
color = "blue",
size = 0.5) +
labs(title = "Histogram of Daily Steps",
x = "Daily Steps",
y = "Count") +
facet_grid(. ~ data) +
theme_light() +
theme(legend.position = "none")
# Spread daily data frame to create summary table
activity.daily.wide <- spread(activity.daily.long, data, steps) %>%
rename(original.steps = original, imputed.steps = imputed)
# Get mean and median summaries
knitr::kable(summary(activity.daily.wide)[c(3,4), c(2,3)])
```
- Mean and median values differ from the first part of the assignment—after imputation, mean and median values are smaller compared to the original data
- Imputing missing data estimated zeros for almost all of the NAs, slightly shifting the distribution to the left
## Are there differences in activity patterns between weekdays and weekends?
*Create a new factor variable in the dataset with two levels, "weekday" and "weekend", indicating whether a given date is a weekday or weekend day.*
```{r Q5.1}
activity.weekdays.imputed <- mutate(activity, weekdays = weekdays(date)) %>%
# Create new column reclassifying M-F as weekday and S-S as weekend
mutate(weekends = ifelse(weekdays == "Saturday" | weekdays == "Sunday",
"Weekend", "Weekday")) %>%
select(-c(steps, weekdays)) %>%
rename(steps = steps.imputed,
weekdays = weekends)
```
*Make a panel plot containing a time series plot of the 5-minute interval (x-axis) and the average number of steps taken, averaged across all weekday days or weekend days (y-axis).*
```{r Q5.2}
# Calculate interval averages for weekday and weekend data
activity.weekdays.interval <- group_by(activity.weekdays.imputed,
weekdays,
interval) %>%
summarize(avg.steps = mean(steps, na.rm = T))
ggplot(activity.weekdays.interval, aes(interval, avg.steps, color = weekdays)) +
geom_line() +
facet_wrap(. ~ weekdays) +
labs(title = "Daily Average Number of Steps",
x = "5-Minute Interval",
y = "Average Number of Steps") +
theme_light() +
theme(legend.position = "none")
```