如何将JSON对象(在文件中)中的数据读入R?

use*_*217 5 json r

我是R的新手,并没有太多的编程接触.我在将文件(包含JSON对象)加载到R时遇到问题

> library(rjson)
> jsonFile <- "C:\\Users\\jsonRecords.txt"
> jsonData <- fromJSON( jsonFile, method = "C", unexpected.escape = "error" )
Error in fromJSON(jsonFile, method = "C", unexpected.escape = "error") : 
  unexpected character 'C'
Run Code Online (Sandbox Code Playgroud)

我想将数据读入R进行进一步分析..任何帮助将不胜感激.

谢谢

ags*_*udy 11

试试吧:

    fromJSON( file = json_file )
Run Code Online (Sandbox Code Playgroud)

它会读取所有文件.这里有一个例子:

write(toJSON( iris ),'jstest')
res <- fromJSON( file="jstest")

str(res)
List of 5
 $ Sepal.Length: num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num [1:150] 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num [1:150] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num [1:150] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : chr [1:150] "setosa" "setosa" "setosa" "setosa" ...
Run Code Online (Sandbox Code Playgroud)


Ric*_*rta 5

看起来你所缺少的只是file=争论

fromJSON( file = json_file, method = "C", unexpected.escape = "error" )
Run Code Online (Sandbox Code Playgroud)

如果你看看 args(fromJSON)

 > args(fromJSON)
 function (json_str, file, method = "C", unexpected.escape = "error") 
Run Code Online (Sandbox Code Playgroud)

你会看到第一个参数是json_str,第二个是file.由于您只提供第二个参数,因此必须明确告诉函数您要提供的是什么. (否则,它认为你的json_file字符串是一个json对象,它将尝试将其视为这样..因此错误.)