
- R 教程
- R - 首頁
- R - 概述
- R - 環境設定
- R - 基本語法
- R - 資料型別
- R - 變數
- R - 運算子
- R - 決策
- R - 迴圈
- R - 函式
- R - 字串
- R - 向量
- R - 列表
- R - 矩陣
- R - 陣列
- R - 因子
- R - 資料框
- R - 包
- R - 資料重塑
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 檔案使用 **fromJSON()** 函式由 R 讀取。它作為 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
廣告