2017-08-31 54 views
1

我有一個簡單的json字符串,我通過URL讀入。如何從JSON訪問正確的數據幀列名稱

jsonFile <- jsonlite::fromJSON(RCurl::getURL("http://server.com/jsonData.php")) 

[ 
    { 
    "X": "A", 
    "Y": 1, 
    "Z": 2 
    }, 
    { 
    "X": "B", 
    "Y": 3, 
    "Z": 4 
    }, 
    { 
    "X": "C", 
    "Y": -4, 
    "Z": -3 
    }, 
    { 
    "X": "D", 
    "Y": -2, 
    "Z": -1 
    } 
] 

我然後嘗試基於數值對列進行顏色編碼。如果Y或Z列爲正則爲綠色,否則爲紅色。我嘗試這個具有以下功能:

DT::formatStyle(jsonFile, c('Y', 'Z'), color = 'white', backgroundColor = styleInterval(0, c('green','red'))) 

但它產生這個錯誤:錯誤name2int(姓名,名稱,rownames): 您指定的列:X,Y,但對列名數據

當我調用數據框函數的名字,我得到:

names(jsonFile) 
[1] "X" "Y" "Z" 

我覺得這與我是如何訪問數據做框架本身,因爲它來自JSON數據結構,但我還沒有加密如何正確調用列名稱。在使用管道時也遇到同樣的問題。

任何幫助,非常感謝。

感謝

回答

0

這是不符合JSON到data.frame轉換的問題,而是從DT格式化您嘗試

從幫助文件?formatStyle

table - a table objet created from datatable()

因此,需要從datatable()函數創建到formatStyle的輸入。你可以在你的函數調用直接做到這一點:

formatStyle(datatable(jsonFile), c('Y', 'Z'), color = 'white', 
      backgroundColor = styleInterval(0, c('green','red'))) 

enter image description here