将JSON URL转换为R数据框 [英] Convert JSON URL to R Data Frame
问题描述
我在将JSON文件(从API)转换为R中的数据帧时遇到麻烦.URL
I'm having trouble converting a JSON file (from an API) to a data frame in R. An example is the URL http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2010&week=1&format=json
我尝试了来自S/O的一些不同建议,包括 将json数据转换为R中的数据框和各种博客文章例如 http://zevross.com/blog/2015/02/12/using-r-to-download-and-parse-json-an-example-using-data -from-open-data-portal/
I've tried a few different suggestions from S/O, including convert json data to data frame in R and various blog posts such as http://zevross.com/blog/2015/02/12/using-r-to-download-and-parse-json-an-example-using-data-from-an-open-data-portal/
我最近一直在使用下面的代码,它为我提供了一个大矩阵,其中包含4个行"和一堆变量"(V1,V2等).我假设此JSON文件的格式与普通"文件的格式不同.
The closest I've been is using the code below which gives me a large matrix with 4 "rows" and a bunch of "varables" (V1, V2, etc.). I'm assuming that this JSON file is in a different format than "normal" ones.
library(RJSONIO)
raw_data <- getURL("http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2010&week=1&format=json")
data <- fromJSON(raw_data)
final_data <- do.call(rbind, data)
我对如何使其工作完全不可知,因此欢迎任何R包/过程.提前致谢.
I'm pretty agnostic as to how to get it to work so any R packages/process are welcome. Thanks in advance.
推荐答案
此JSON没有什么异常"之处,它不是简单地适合数据框架的矩形结构. JSON可以表示更丰富的数据结构.
There's nothing "abnormal" about this JSON, its just not a rectangular structure that fits trivially into a data frame. JSON can represent much richer data structures.
例如(使用rjson
包,您没有说过使用的内容):
For example (using the rjson
package, you've not said what you've used):
> data = rjson::fromJSON(file="http://api.fantasy.nfl.com/v1/players/stats?statType=seasonStats&season=2010&week=1&format=json")
> length(data[[4]][[10]]$stats)
[1] 14
> length(data[[4]][[1]]$stats)
[1] 21
(data[[1 to 3]]
看起来像标题)
data[[4]]
的第10个元素的统计"有14个元素,第一个元素的统计"有21个元素.如何适应矩形数据框? R已将其存储在列表中,因为这是R存储不规则数据结构的最佳方法.
the "stats" of the 10th element of data[[4]]
has 14 elements, the "stats" of the first has 21. How is that going to fit into a rectangular data frame? R has stored it in a list because that's R's best way of storing irregular data structures.
除非您可以定义将不规则数据映射到矩形数据框中的方法,否则不能将其存储在数据框中.您了解数据的结构吗?这是必不可少的.
Unless you can define a way of mapping the irregular data into a rectangular data frame, you can't store it in a data frame. Do you understand the structure of the data? That's essential.
这篇关于将JSON URL转换为R数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!