Retrieving, Loading and preprocessing the data

dataURL<-"https://d396qusza40orc.cloudfront.net/repdata%2Fdata%2Factivity.zip"


dlfile1<-"activity.zip"

if(!file.exists(dlfile1)) {
  download.file(dataURL, destfile = dlfile1, method = "curl")
  unzip(dlfile1, exdir = ".")
}

unzip(zipfile="activity.zip")
data <- read.csv("activity.csv")

Average Steps per Day

library(ggplot2)
total.steps <- tapply(data$steps, data$date, FUN=sum, na.rm=TRUE)
qplot(total.steps, binwidth=1000, col="red", xlab="total number of steps taken each day")

mean(total.steps, na.rm=TRUE)
## [1] 9354.23
median(total.steps, na.rm=TRUE)
## [1] 10395

Average Daily Activity Pattern

library(ggplot2)

averages <- aggregate(x=list(steps=data$steps), by=list(interval=data$interval),
                      FUN=mean, na.rm=TRUE)
ggplot(data=averages, aes(x=interval, y=steps)) +
    geom_line(col="red") +
    xlab("5-minute interval") +
    ylab("average number of steps taken")

5-minute interval with Max steps

averages[which.max(averages$steps),]
##     interval    steps
## 104      835 206.1698

Imputing missing values

Filter Missing Values

missing <- is.na(data$steps)
# How many missing
table(missing)
## missing
## FALSE  TRUE 
## 15264  2304

Fill the missing values with mean values

# Replace each missing value with the mean value of its 5-minute interval
fill.value <- function(steps, interval) {
    filled <- NA
    if (!is.na(steps))
        filled <- c(steps)
    else
        filled <- (averages[averages$interval==interval, "steps"])
    return(filled)
}
filled.data <- data
filled.data$steps <- mapply(fill.value, filled.data$steps, filled.data$interval)

Make the histogram per day

total.steps <- tapply(filled.data$steps, filled.data$date, FUN=sum)
qplot(total.steps, binwidth=1000, col="green", xlab="total number of steps taken each day")

mean(total.steps)
## [1] 10766.19
median(total.steps)
## [1] 10766.19

Weekday or Weekend Pattern difference

First, let’s find the day of the week for each measurement in the dataset. In this part, we use the dataset with the filled-in values.

weekday.or.weekend <- function(date) {
    day <- weekdays(date)
    if (day %in% c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday"))
        return("weekday")
    else if (day %in% c("Saturday", "Sunday"))
        return("weekend")
    else
        stop("invalid date")
}
filled.data$date <- as.Date(filled.data$date)
filled.data$day <- sapply(filled.data$date, FUN=weekday.or.weekend)

Plot seperately for weekday or weekend

averages <- aggregate(steps ~ interval + day, data=filled.data, mean)
ggplot(averages, aes(interval, steps)) + geom_line() + facet_grid(day ~ .) +
    xlab("5-minute interval") + ylab("Number of steps")