Repository navigation
Expand file tree
/
Copy pathplot2.R
More file actions
69 lines (54 loc) · 2.18 KB
/
Copy pathplot2.R
File metadata and controls
69 lines (54 loc) · 2.18 KB
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
# ------------------ Libraries ---------------
library(plyr)
library(dplyr)
# ------------------ 1- File Downloading ---------------
if (!file.exists( "./data" )) {
dir.create( "./data" )
}
zipfile = "./data/exdata%2Fdata%2Fhousehold_power_consumption.zip"
if ( !file.exists( zipfile ) ) {
print( "Dowloading file ..." )
fileUrl1 = "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
print( paste("From" , fileUrl1) )
download.file( fileUrl1 , destfile = zipfile)
} else {
print( "Download file already exists." )
}
# ------------------ 2- File Extracting ---------------
datafile = "./data/household_power_consumption.txt"
if ( !file.exists( datafile ) ) {
print( "Extracting folder ..." )
unzip(zipfile , exdir = "./data")
} else {
print( "Unzipped file already exists." )
}
# ------------------ 3- Data reading ---------------
# To read just the needed data:
# Getting the names:
power_names = read.table(file = datafile, sep = ";" , header = TRUE,
na.strings = "?", nrows = 10)
# Getting the dates:
power_dates = read.table(file = datafile, sep = ";" , header = TRUE,
na.strings = "?", nrows = 70000,
colClasses = c(NA, rep("NULL" , 8)) )
# First interest date:
first = head( which(power_dates == "1/2/2007" ) , 1)
# Last interest date:
last = tail( which(power_dates == "2/2/2007" ) , 1) + 1
# Reading just the needed data
power = read.table(file = datafile, sep = ";" , header = FALSE,
na.strings = "?", nrows = last - first ,
skip = first , col.names = names(power_names))
# ------------------ 4- Plot 2 ---------------
# Plot
plot(
strptime( paste0(power$Date, " ", power$Time), "%d/%m/%Y %H:%M:%S" )
, power$Global_active_power, type = "l", xlab = "",
ylab = "Global Active Power (kilowatts)" )
# plot2.png
png(filename = "plot2.png", width = 480, height = 480, units = "px" )
plot(
strptime( paste0(power$Date, " ", power$Time), "%d/%m/%Y %H:%M:%S" )
, power$Global_active_power, type = "l", xlab = "",
ylab = "Global Active Power (kilowatts)" )
dev.off()