-
Notifications
You must be signed in to change notification settings - Fork 37.1k
/
Copy pathPA1_template.Rmd
227 lines (149 loc) · 6.13 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
---
title: "Reproducible Research: Peer Assessment 1"
output:
html_document:
keep_md: true
---
## Introduction
This is an R Markdown document, created for the Coursera course "Reproducible Research", in completion of "Peer Assessment 1". The assignment requires students to write an R markdown document evidencing literate programming, using markdown and R programming techniques. There are 5 primary questions to be answered, dealing with processing and analysing data. The data provided to be worked upon, is called "activity monitoring data".
## Loading and preprocessing the data
```{r}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, fig.width = 10, fig.height = 5,
fig.keep = 'all' ,fig.path = 'figures\ ', dev = 'png')
```
```{r}
# Loading packages
library(ggplot2)
library(ggthemes)
# Unzipping the file and reading it
path = getwd()
unzip("repdata_data_activity.zip", exdir = path)
activity <- read.csv("activity.csv")
# Setting date format to help get the weekdays of the dates
activity$date <- as.POSIXct(activity$date, "%Y%m%d")
# Getting the days of all the dates on the dataset
day <- weekdays(activity$date)
# Combining the dataset with the weekday of the dates
activity <- cbind(activity, day)
# Viewing the processed data
summary(activity)
```
## What is mean total number of steps taken per day?
```{r}
# Calculating total steps taken on a day
activityTotalSteps <- with(activity, aggregate(steps, by = list(date), sum, na.rm = TRUE))
# Changing col names
names(activityTotalSteps) <- c("Date", "Steps")
# Converting the data set into a data frame to be able to use ggplot2
totalStepsdf <- data.frame(activityTotalSteps)
# Plotting a histogram using ggplot2
g <- ggplot(totalStepsdf, aes(x = Steps)) +
geom_histogram(breaks = seq(0, 25000, by = 2500), fill = "#83CAFF", col = "black") +
ylim(0, 30) +
xlab("Total Steps Taken Per Day") +
ylab("Frequency") +
ggtitle("Total Number of Steps Taken on a Day") +
theme_calc(base_family = "serif")
print(g)
```
The mean of the total number of steps taken per day is:
```{r}
mean(activityTotalSteps$Steps)
```
The median of the total number of steps taken per day is:
```{r}
median(activityTotalSteps$Steps)
```
## What is the average daily activity pattern?
```{r}
# Calculating the average number of steps taken, averaged across all days by 5-min intervals.
averageDailyActivity <- aggregate(activity$steps, by = list(activity$interval),
FUN = mean, na.rm = TRUE)
# Changing col names
names(averageDailyActivity) <- c("Interval", "Mean")
# Converting the data set into a dataframe
averageActivitydf <- data.frame(averageDailyActivity)
# Plotting on ggplot2
da <- ggplot(averageActivitydf, mapping = aes(Interval, Mean)) +
geom_line(col = "blue") +
xlab("Interval") +
ylab("Average Number of Steps") +
ggtitle("Average Number of Steps Per Interval") +
theme_calc(base_family = "serif")
print(da)
```
Which 5-minute interval, on average across all the days in the dataset, contains the maximum number of steps?
```{r}
averageDailyActivity[which.max(averageDailyActivity$Mean), ]$Interval
```
## Imputing missing
Calculate and report the total number of missing values in the dataset (i.e. the total number of rows with NAs.
```{r}
sum(is.na(activity$steps))
```
Devise a strategy for filling in all of the missing values in the dataset. The strategy does not need to be sophisticated. For example, you could use the mean/median for that day, or the mean for that 5-minute interval, etc.
```{r}
# Matching the mean of daily activity with the missing values
imputedSteps <- averageDailyActivity$Mean[match(activity$interval, averageDailyActivity$Interval)]
```
Create a new dataset that is equal to the original dataset but with the missing data filled in.
```{r}
# Transforming steps in activity if they were missing values with the filled values from above.
activityImputed <- transform(activity,
steps = ifelse(is.na(activity$steps), yes = imputedSteps, no = activity$steps))
# Forming the new dataset with the imputed missing values.
totalActivityImputed <- aggregate(steps ~ date, activityImputed, sum)
# Changing col names
names(totalActivityImputed) <- c("date", "dailySteps")
```
Testing the new dataset to check if it still has any missing values -
```{r}
sum(is.na(totalActivityImputed$dailySteps))
```
```{r}
# Converting the data set into a data frame to be able to use ggplot2
totalImputedStepsdf <- data.frame(totalActivityImputed)
# Plotting a histogram using ggplot2
p <- ggplot(totalImputedStepsdf, aes(x = dailySteps)) +
geom_histogram(breaks = seq(0, 25000, by = 2500), fill = "#83CAFF", col = "black") +
ylim(0, 30) +
xlab("Total Steps Taken Per Day") +
ylab("Frequency") +
ggtitle("Total Number of Steps Taken on a Day") +
theme_calc(base_family = "serif")
print(p)
```
The mean of the total number of steps taken per day is:
```{r}
mean(totalActivityImputed$dailySteps)
```
The median of the total number of steps taken per day is:
```{r}
median(totalActivityImputed$dailySteps)
```
## 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}
# Updating format of the dates
activity$date <- as.Date(strptime(activity$date, format="%Y-%m-%d"))
# Creating a function that distinguises weekdays from weekends
activity$dayType <- sapply(activity$date, function(x) {
if(weekdays(x) == "Saturday" | weekdays(x) == "Sunday")
{y <- "Weekend"}
else {y <- "Weekday"}
y
})
```
```{r}
# Creating the data set that will be plotted
activityByDay <- aggregate(steps ~ interval + dayType, activity, mean, na.rm = TRUE)
# Plotting using ggplot2
dayPlot <- ggplot(activityByDay, aes(x = interval , y = steps, color = dayType)) +
geom_line() + ggtitle("Average Daily Steps by Day Type") +
xlab("Interval") +
ylab("Average Number of Steps") +
facet_wrap(~dayType, ncol = 1, nrow=2) +
scale_color_discrete(name = "Day Type") +
theme_calc(base_family = "serif")
print(dayPlot)
```