欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

R语言处理JSON文件的方法

程序员文章站 2022-06-28 14:54:40
json文件以人类可读格式将数据存储为文本。 json代表javascript object notation。 r可以使用rjson包读取json文件。安装rjson包在r语言控制台中,您可以发出以...

json文件以人类可读格式将数据存储为文本。 json代表javascript object notation。 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转换为数据帧

我们可以使用as.data.frame()函数将上面提取的数据转换为r语言数据帧以进行进一步分析。

# 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,   start_date,     dept
1      1    rick     623.30    2012-01-01      it
2      2    dan      515.20    2013-09-23      operations
3      3    michelle 611.00    2014-11-15      it
4      4    ryan     729.00    2014-05-11      hr
5     na    gary     843.25    2015-03-27      finance
6      6    nina     578.00    2013-05-21      it
7      7    simon    632.80    2013-07-30      operations
8      8    guru     722.50    2014-06-17      finance

到此这篇关于r语言处理json文件的方法的文章就介绍到这了,更多相关r语言对json文件操作内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: R语言 JSON