登录
首页精彩阅读R语言处理JSON文件
R语言处理JSON文件
2017-06-18
收藏

R语言处理JSON文件

JSON文件数据存储在人类可读格式的文本。 JSON代表JavaScript对象符号。 R能够使用rjson包读取JSON文件。

安装rjson软件包

在R控制台可以发出以下命令来安装 rjson 软件包。

install.packages("rjson")

输入数据

通过下面的数据复制到记事本等文本编辑器创建一个JSON文件。保存以 .json 扩展名的文件,并选择文件类型为所有文件(*.*)。

{
"ID":["1","2","3","4","5","6","7","8" ],
"Name":["Rick","Dan","Michelle","Ryan","Gary","Nina","Simon","Guru" ],
"Salary":["623.3","515.2","611","729","843.25","578","632.8","722.5" ],
"StartDate":[ "1/1/2012","9/23/2013","11/15/2014","5/11/2014","3/27/2015","5/21/2013","7/30/2013","6/17/2014"],
"Dept":[ "IT","Operations","IT","HR","Finance","IT","Operations","Finance"]
}

读取JSON文件

JSON文件是由R使用函数 JSON()读取。它存储为在R列表

# Load the package required to read JSON files.
library("rjson")

# Give the input file name to the function.
result <- fromJSON(file="input.json")

# Print the result.
print(result

当我们上面的代码执行时,它产生以下结果:

$ID
[1] "1" "2" "3" "4" "5" "6" "7" "8"

$Name
[1] "Rick"     "Dan"      "Michelle" "Ryan"     "Gary"     "Nina"     "Simon"    "Guru"    

$Salary
[1] "623.3"  "515.2"  "611"    "729"    "843.25" "578"    "632.8"  "722.5"

$StartDate
[1] "1/1/2012"   "9/23/2013"  "11/15/2014" "5/11/2014"  "3/27/2015"  "5/21/2013"  "7/30/2013"  "6/17/2014"

$Dept
[1] "IT"         "Operations" "IT"         "HR"         "Finance"    "IT"         "Operations" "Finance" 

转换JSON为数据帧

我们可以将所提取上述的数据到一个R数据帧进一步分析。使用as.data.frame()函数。

# Load the package required to read JSON files.
library("rjson")

# Give the input file name to the function.
result <- fromJSON(file="input.json")

# Convert JSON file to a data frame.
json_data_frame <- as.data.frame(result)

print(json_data_frame)

当我们上面的代码执行时,它产生以下结果:

  ID     Name Salary  StartDate       Dept
1  1     Rick  623.3   1/1/2012         IT
2  2      Dan  515.2  9/23/2013 Operations
3  3 Michelle    611 11/15/2014         IT
4  4     Ryan    729  5/11/2014         HR
5  5     Gary 843.25  3/27/2015    Finance
6  6     Nina    578  5/21/2013         IT
7  7    Simon  632.8  7/30/2013 Operations
8  8     Guru  722.5  6/17/2014    Finance

数据分析咨询请扫描二维码

客服在线
立即咨询