R JSON文件

JSON文件以人类可读格式将数据存储为文本。 Json代表JavaScript Object Notation。 R可以使用rjson包读取JSON文件。

安装rjson包

在R语言控制台中,您可以发出以下命令来安装rjson包。

  1. install.packages("rjson")

输入数据

通过将以下数据复制到文本编辑器(如记事本)中来创建JSON文件。 使用.json扩展名保存文件,并将文件类型选择为所有文件(.)。

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

读取JSON文件

JSON文件由R使用来自JSON()的函数读取。 它作为列表存储在R中。

  1. # Load the package required to read JSON files.
  2. library("rjson")
  3. # Give the input file name to the function.
  4. result <- fromJSON(file = "input.json")
  5. # Print the result.
  6. print(result)

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

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

将JSON转换为数据帧

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

  1. # Load the package required to read JSON files.
  2. library("rjson")
  3. # Give the input file name to the function.
  4. result <- fromJSON(file = "input.json")
  5. # Convert JSON file to a data frame.
  6. json_data_frame <- as.data.frame(result)
  7. print(json_data_frame)

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

  1. id, name, salary, start_date, dept
  2. 1 1 Rick 623.30 2012-01-01 IT
  3. 2 2 Dan 515.20 2013-09-23 Operations
  4. 3 3 Michelle 611.00 2014-11-15 IT
  5. 4 4 Ryan 729.00 2014-05-11 HR
  6. 5 NA Gary 843.25 2015-03-27 Finance
  7. 6 6 Nina 578.00 2013-05-21 IT
  8. 7 7 Simon 632.80 2013-07-30 Operations
  9. 8 8 Guru 722.50 2014-06-17 Finance