Function to download data from the EIA's API via R stopped working why? -
i'm trying figure out why function download data eia stopped working. why did following code stop working?
getwdeia <- function(id, key) { id <- unlist(strsplit(id, ";")) key <- unlist(strsplit(key, ";")) url <- paste("http://api.eia.gov/series?series_id=", id, "&api_key=", key, "&out=xml", sep = "") doc <- xmlparse(file = url, isurl = true) df <- xmltodataframe(nodes = getnodeset(doc, "//data/row")) df <- arrange(df, df$date) date <- as.date(df$date, "%y%m%d") values <- as.numeric(levels(df[, -1]))[df[, -1]] xts_data <- xts(values, order.by = date) names(xts_data) <- sapply(strsplit(id, "-"), paste, collapse = ".") assign(sapply(strsplit(id, "-"), paste, collapse = "."), xts_data, envir = .globalenv) } getwdeia(id = "pet.w_epc0_fpf_r48_mbbld.4", key = key)
it seems did not @ raw xml api before posting question here. there no //data/row
xpath:
<?xml version="1.0" encoding="utf-8"?> <eia_api> <request> <command>series</command> <series_id>pet.w_epc0_fpf_r48_mbbld.4</series_id> </request> <series> <row> <series_id>pet.w_epc0_fpf_r48_mbbld.4</series_id> <name>lower 48 states field production of crude oil, 4 week avg</name> <units>thousand barrels per day</units> <f>4</f> <unitsshort>mbbl/d</unitsshort> <description>lower 48 states field production of crude oil</description> <copyright>none</copyright> <source>eia, u.s. energy information administration</source> <start/> <end/> <updated>2015-08-05t13:14:06-0400</updated> <data/> </row> </series> </eia_api>
you didn't include 2 necessary library
calls. modified function below returns data frame correctly targeted path:
library(xml) library(dplyr) getwdeia <- function(id, key) { id <- unlist(strsplit(id, ";")) key <- unlist(strsplit(key, ";")) url <- paste("http://api.eia.gov/series?series_id=", id, "&api_key=", key, "&out=xml", sep = "") doc <- xmlparse(file = url, isurl = true) df <- xmltodataframe(nodes = getnodeset(doc, "//series/row")) return(df) } val <- getwdeia(id = "pet.w_epc0_fpf_r48_mbbld.4", key = "e7fdccba39fba0268555b7e81d73cd47")
if @ data frame returned, seem not data expecting:
glimpse(val) ## observations: 1 ## variables: ## $ series_id (fctr) pet.w_epc0_fpf_r48_mbbld.4 ## $ name (fctr) lower 48 states field production of crude oil, 4 week avg ## $ units (fctr) thousand barrels per day ## $ f (fctr) 4 ## $ unitsshort (fctr) mbbl/d ## $ description (fctr) lower 48 states field production of crude oil ## $ copyright (fctr) none ## $ source (fctr) eia, u.s. energy information administration ## $ start (fctr) ## $ end (fctr) ## $ updated (fctr) 2015-08-05t13:14:06-0400 ## $ data (fctr)
perhaps try id?
Comments
Post a Comment