运行代码并尝试将数据集导出到电子表格或txt.file后,我遇到了困难。 我是R的新手,所以也许这个问题很简单。
运行以下代码后:
eia_series <- function(api_key, series_id, start = NULL, end = NULL, num = NULL, tidy_data = "no", only_data = FALSE){
# max 100 series
# test if num is not null and either start or end is nut null. Not allowed
# api_key test for character.
# series_id test for character.
# if start/end not null, then check if format matches series id date format
# parse date and numerical data
# parse url
series_url <- httr::parse_url("http://api.eia.gov/series/")
series_url$query$series_id <- paste(series_id, collapse = ";")
series_url$query$api_key <- api_key
series_url$query$start <- start
series_url$query$end <- end
series_url$query$num <- num
# get data
series_data <- httr::GET(url = series_url)
series_data <- httr::content(series_data, as = "text")
series_data <- jsonlite::fromJSON(series_data)
# Move data from data.frame with nested list and NULL excisting
series_data$data <- series_data$series$data
series_data$series$data <- NULL
# parse data
series_data$data <- lapply(X = series_data$data,
FUN = function(x) data.frame(date = x[, 1],
value = as.numeric(x[, 2]),
stringsAsFactors = FALSE))
# add names to the list with data
names(series_data$data) <- series_data$data
# parse dates
series_data$data <- eia_date_parse(series_list = series_data$data, format_character = series_data$series$f)
# tidy up data
if(tidy_data == "tidy_long"){
series_data$data <- lapply(seq_along(series_data$data),
function(x) {cbind(series_data$data[[x]],
series_time_frame = series_data$series$f[x],
series_name = series_data$series$series_id[x],
stringsAsFactors = FALSE)})
series_data$data <- do.call(rbind, series_data$data)
}
# only data
if(only_data){
series_data <- series_data$data
}
return(series_data)
}
运行功能后
eia_series(api_key = "XXX",series_id = c("PET.MCRFPOK1.M", "PET.MCRFPOK2.M"))
我试图&#34;转移&#34;数据以便导出但出现以下错误:
未提供编码:默认为UTF-8。
我不明白为什么。你能救我一下吗?
答案 0 :(得分:2)
这看起来不像是错误,而是一种陈述。可能来自httr::content(series_data, as = "text")
。查看正文部分的https://cran.r-project.org/web/packages/httr/vignettes/quickstart.html。只要您的数据返回您期望的内容,这应该不是问题。否则你可以尝试不同的编码或其他地方有一个错误。
答案 1 :(得分:1)
尝试:
series_data <- httr::content(series_data, as = "text", encoding = "UTF-8")