forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot2.R
More file actions
87 lines (65 loc) · 3.74 KB
/
Copy pathplot2.R
File metadata and controls
87 lines (65 loc) · 3.74 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
## *** Coursera Exploratory Data Analysis - Project 1 ***
##
## Script name: plot2.R (created using R 3.1.1 on Windows 7)
##
## See README.md for details on the assignment and source data used.
## Download source data and extract household_power_consumption.txt file first
##
## Important: The script expects data in working directory of R. The code prompts
## and checks existence of file first. It terminates if file is not found.
##
## The main code is implemented in a function named run(). Source the script file
## into R enviroment and execute run() to begin.
##
## The code first reads the data for the two days from file and creates a dataset (data.use)
## in memory, applying column classes and names to suit the analysis.
## strptime function is used to convert the original character data in Date and Time columns,
## which is then added to the dataset as a new variable of class Date/Time and used later
## for the plot generation. The plot code targets png file device in working directory
## and it is repeated for screen display as well.
fileCheck <- function () {
resp <- readline("Is household_power_consumption.txt in working directory? [y/n]? ")
if(tolower(substr(resp,1,1)) == "n")
stop("Please see README.md before continuing. Ending script..")
dir.use <- getwd() # expects data in working directory
cat(paste0("\nChecking in ", dir.use,".." ))
if (!file.exists(paste0(dir.use, "/household_power_consumption.txt"))) {
stop("Data file not found! Please see README.md for download instructions.")
}
dir.use #return data directory
}
## Main function
run <- function() {
## test existence of data file to begin with
dir.use <- tryCatch({fileCheck()}, error = function(e) { stop(e)} )
## Data is rectangular and contains header as in README.md. We can read a few rows
# at the start and use it to determine column classes and column names
# for use later in the script. Could have created the vectors manually as well.
top5rows <- read.table("household_power_consumption.txt",
header=TRUE, nrows=5, sep=";", stringsAsFactors=FALSE, na.strings=c("?", "NA"))
classes <- sapply(top5rows, class) ## using R's class function
cat ("\nDataset has columns with classes:\n ")
#cat(names(top5rows), "\n")
cat(classes, "\n")
## 1. Read data for use in analysis
# Read only two days data from the large dataset
# First get a handle to file in working directory. Need read access only
fc <- file("household_power_consumption.txt", "r")
# Read text and extract lines that match dd/mm/yyyy formated
# days 1 and 2 of Feb, 2007
cat("\nReading large data....do not interrupt...\n")
data.use <- read.table(text=grep("^(0?[1,2])/(0?2)/2007", readLines(fc), value=TRUE),
header=F, sep=";", stringsAsFactors=FALSE, na.strings=c("?", "NA"),
colClasses=classes, col.names=names(top5rows), check.names=FALSE)
close(fc) # close connection to file
## create new datetime variable from Date and Time character data
# Note, strptime converts and new variable gets Date/Time class
data.use <- transform(data.use, datetime = strptime(paste(Date,Time), format="%d/%m/%Y %H:%M:%S"))
## Data ready..begin plot
cat ("\nCreating plot2.png in ", dir.use, "\n ")
png(file="plot2.png", width=480, height=480, units = "px") ## Open PNG device
with(data.use, plot(datetime, Global_active_power, type="l",
xlab="", ylab="Global Active Power (kilowatts)") )
d <- dev.off() # turn PNG graphics device off
cat("\n", normalizePath("plot2.png"),"..is ready for viewing!")
} ## end of run()