将R data.frame转换为热图概念的特定json文件

时间:2016-04-08 11:11:30

标签: json r

我在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 ]]
}

有没有具体的方法,如何以最简单的方式做到这一点?我真的不知道我应该从哪里开始。非常感谢您提前提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

我们可以使用$(".js-example-basic-hide-search").select2({ minimumResultsForSearch: Infinity }); 中的toJSON jsonlite,将names和数据(从最后一行反转到第一行)放在已命名的list中。

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]]
 }