forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plot3.R
64 lines (59 loc) · 2.74 KB
/
plot3.R
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
# Exploratory Data Analysis couse - Course Project 1
# Author: Adam Grodowski (adam.grodowski@gmail.com)
library(data.table)
PrepareHouseholdPowerData <- function(file, cols, filter) {
# Extracts and refines the relevant observations and variables using fread
# optimised to retrieve selected columns and rows only. Requires 'data.table'.
#
# Args:
# file: The file with household power consumption data.
# cols: A character vector with variable types. Use 'NULL' to
# skip that column. Must have 9 values, one for each column.
# filter: A logical closure for filtering the data rows.
#
# Returns:
# A data.table object with initially selected variables that satisfy
# given filter with the following variables added (+) and removed (-):
# (+) DateTime: a POSIXct object computed from Date and Time variables
# in %d/%m/%Y %H:%M:%S format.
# (-) Date, Time: as not needed anymore
# Error handling
if (length(cols) != 9)
stop("There must be 9 values provided in cols, one for each column.
Use 'NULL to skip that column")
if (!file.exists(file))
stop("File does not exist!")
data <- fread(file, colClasses=cols, select=which(cols!="NULL"),
sep=';', header=T, na.strings=c("?"))
datawant <- filter(data) # subset rows using provided filter
timestamp <- paste(datawant$Date, datawant$Time)
datawant[, DateTime := as.POSIXct(timestamp, format="%d/%m/%Y %H:%M:%S")]
datawant[, c("Date","Time") := NULL] # drops variables not needed anymore
}
# Retrieve dataset (if not present)
file <- "household_power_consumption.txt"
if (!file.exists(file)) {
download.file(
"https://d396qusza40orc.cloudfront.net/exdata/data/household_power_consumption.zip",
"household_power_consumption.zip",method="curl")
unzip("household_power_consumption.zip")
}
# Prepare column types and filter closure for data loading
cols <- rep("NULL",9) # initially nullify all columns
cols[1:2] <- "character" # Date & Time, it is faster to read as chars
cols[7:9] <- "numeric"
filter <- function(dt)
dt[Date %in% c("1/2/2007","2/2/2007")] # only rows wihtin 1-2/2/2007
# Extract only relevant and needed data
data <- PrepareHouseholdPowerData(file, cols, filter)
# Plot 3 - Sub metering through time
png(filename="plot3.png",width=480, height=480)
with(data, {
plot(DateTime,Sub_metering_1, type="l",xlab="",ylab="Energy sub metering")
lines(DateTime,Sub_metering_2, type="l",xlab="",col="red")
lines(DateTime,Sub_metering_3, type="l",xlab="",col="blue")
legend("topright",
legend = c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),
col = c("black","red","blue"), lty= 1)
})
dev.off()