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