-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEIA_API_query.R
40 lines (31 loc) · 1.12 KB
/
EIA_API_query.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
# script to access the EIA's beta API, convert data, then plot
# requires a unique API key which can be obtained at: http://www.eia.gov/beta/api/
require(RCurl)
require(plyr)
require(jsonlite)
#series
series = "ELEC.PRICE."
#Two letter state abbreviation
state = "TX"
#Type All = All, Residential =
type = "ALL"
#Time A = Annual, M = Monthly, Q = Quarterly
time_step = "A"
#API Key
key <- scan("/Users/jim/Documents/R/private_EIA_API_key.txt", what = "character")
#Create API url
id<-paste(series,state,"-",type,".",time_step, sep="")
api<-paste("http://api.eia.gov/series/data?api_key=",key,"&series_id=",id, sep="")
#Get data via RCurl
data_json<-getURL(api, followlocation = TRUE)
#Convert JSON format to R format, then flatten structure
data_nested <- fromJSON(data_json)
data_flat <- flatten(as.data.frame(data_nested))
data <- data_flat$series_data.data
data<-data.frame(data)
#need to pass names from selected series as variables instead of specifying string?
names(data)<-c('YEAR', 'ELEC.PRICE')
data$ELEC.PRICE<-as.numeric(data$ELEC.PRICE)
data$YEAR<-as.Date(data$YEAR, "%Y")
#graph test
plot(data, main = id, type = "b")