[英]Convert R data.frame to specific json file for heatmap concept
我在R中有以下數據框:
df <- data.frame(RowNames <- c("FirstCol","SecondCol","ThirdCol","FourthCol"),
FirstCol <- c(0.4,0.5,0.1,0.2),
SecondCol <- c(0.8,0.6,0.4,0.1),
ThirdCol <- c(0.7,0.1,0.2,0.6),
FourthCol <- c(0.5,0.3,0.1,0.9))
names(df) <- c("RowNames", "FirstCol", "SecondCol", "ThirdCol", "FourthCol")
我喜歡將此數據幀轉換為非常具體的json文件,以進一步提供熱圖繪制概念:
# desired output
{
"x": [ "FirstCol", "SecondCol", "ThirdCol", "FourthCol" ],
"y": [ "FourthCol", "ThirdCol", "SecondCol", "FirstCol" ],
"z": [
[ 0.2, 0.1, 0.6, 0.9 ],
[ 0.1, 0.4, 0.2, 0.1 ],
[ 0.5, 0.6, 0.1, 0.3 ],
[ 0.4, 0.8, 0.7, 0.5 ]]
}
有沒有具體的方法,如何以最簡單的方式做到這一點? 我真的不知道我應該從哪里開始。 非常感謝您提前提供的任何幫助。
我們可以通過在命名list
放置names
和數據(從最后一行反向到第一行)來使用jsonlite
的toJSON
。
library(jsonlite)
toJSON(list(x=names(df)[-1], y=rev(names(df)[-1]),
z=`dimnames<-`(as.matrix(df[nrow(df):1,-1]), NULL)))
{
"x":["FirstCol","SecondCol","ThirdCol","FourthCol"],
"y":["FourthCol","ThirdCol","SecondCol","FirstCol"],
"z":[[0.2,0.1,0.6,0.9],
[0.1,0.4,0.2,0.1],
[0.5,0.6,0.1,0.3],
[0.4,0.8,0.7,0.5]]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.