forked from rdpeng/ExData_Plotting1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot1.R
47 lines (28 loc) · 1.48 KB
/
plot1.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
#install and load dependent packages
# R may throw a warning if the packages are already installed
install.packages(c("dplyr","lubridate"))
library(dplyr)
library(lubridate)
# added code to download zip folder from web if necessary.
# previous code required zip folder to be in working directory
# unzip data file folder into working directory (github clone of repo)
if(!dir.exists("./exdata_data_household_power_consumption.zip"))
{
url <- "https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip"
download.file(url, "exdata_data_household_power_consumption.zip")
}
unzip("./exdata_data_household_power_consumption.zip",exdir = getwd())
#read in data
house_power = read.table("household_power_consumption.txt", header = TRUE, sep = ';')
# create POSIXlt date variable from Date and Time columns
house_power <- mutate(house_power, Date_Time = strptime(paste(Date,Time), format = '%d/%m/%Y %H:%M:%S', tz = 'UTC'))
#convert Dates format easier regex matching
house_power$Date <- as.Date(house_power$Date, format = '%d/%m/%Y')
# use regex to subset dates from 2/1/2007 to 2/2/2007
desired_data <- house_power[grepl("(2007-02-01|2007-02-02)",house_power$Date),]
# open png device. default is 480 x 480
png(filename = "plot1.png")
# create plot 1. Note data must be coerced to numeric
with(desired_data, hist(as.numeric(Global_active_power), col = 'red', xlab = "Global Active Power (kilowatts)" ,main = "Global Active Power"))
# turn off graphics device
dev.off()