forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.R
More file actions
56 lines (42 loc) · 1.54 KB
/
utils.R
File metadata and controls
56 lines (42 loc) · 1.54 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
# A helper method for printing to the console.
p <- function(...) {
cat("[run_analysis.R]", ..., "\n")
}
#this function downloads and extract the zip file if doesn't exit.
downloadExtractData <- function(url, zipFile, targetFile){
if(!file.exists(zipFile)){
#download file.
tryCatch({
download.file(url, destfile = zipFile, method = 'curl')
unzip(zipFile, files=targetFile)
}, error = function(e) {
p("Cannot download or extract specified File.", zipFile)
})
}
}
# Extracts the required data and return the cleaned target data.
prepareData <- function() {
url <- 'https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip'
zipFile <- 'exdata-data-household_power_consumption.zip'
targetFile <- 'household_power_consumption.txt'
downloadExtractData(url, zipFile, targetFile)
# Specify column data types.
cols <- c("character", "character", rep("numeric", 7))
# Read in the required rows.
ds <- read.table(targetFile, header=T, sep=';', na.strings="?", colClasses=cols)
ds <- ds[(ds$Date == "1/2/2007") | (ds$Date == "2/2/2007"),]
#Alternative : ds <- ds[ds$Date %in% c("1/2/2007", "2/2/2007"),]
# Prepare vector with the date and time
dateTime <- paste(ds$Date, ds$Time, sep=' ')
# Convert Date and Time and add dateTime to the dataset.
ds$DateTime <- strptime(dateTime, format="%d/%m/%Y %H:%M:%S")
# Return the data.
ds
}
#This function cache the data
getData <- function(){
if(!exists('cached')){
cached <<- prepareData()
}
cached
}