R語言處理JSON文件的方法
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文件操作內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- R語言對CSV文件操作實例講解
- R語言對Excel文件操作實例
- R語言操作XML文件實例分析
- R語言開發之CSV文件的讀寫操作實現
- mysql根據json字段內容作為查詢條件(包括json數組)檢索數據