0

I have a periodic process in R that yields me a data.frame. I want to use this data.frame to create a dropdown selector with AngularJS.

My final data.frame will look more or less as follows (my real example might have a deeper hierarchical structure):

DF<-data.frame(hie1=c(rep("Cl1",2),"Cl2"),hie2=c("Cl1op1","Cl1op2","Clop1"),
               hie3=c("/first.html","/second.html","/third.html"))

I need to convert that data.frame into a JSON with the following structure :

{
"Cl1":{"Cl1op1":"/first.html","Cl1op2": "/second.html"},
"Cl2":{"Cl2op1":"/third.html"}
}

So far, I have tried all the toJSON commands of the rjson and RJSONIO packages for the data.frame with and without column names:

library(rjson)
#library(RJSONIO)

DF2<-DF
colnames(DF2)<-NULL

cat(toJSON(DF))
cat(toJSON(DF2))

I thought about using reshape2's dcast function beforeusing toJSON, but I do not know what kind of structure I need to achieve my goal.

I also used the functions toJSON2 an toJSONArray from the rCharts with no success.

Is there an appropriate transformation in R to get the output I am looking for?

P.S. (I do not mind having [] instead of {})

EDIT:

I have created a couple of functions (included below) to fulfil my needs. However, they are not too clean and I believe that there must be a better way to perform this transformation in R.

I keep this question open expecting a better solution.

linktwo<-function(V){
  paste0(sapply(V,function(x) paste0("'",toString(x),"'")),collapse=":")
}

pastehier<-function(DF){
  if(ncol(DF)==2){
    return(paste0(apply(DF,1,linktwo),collapse=","))
  }else{
    u<-unique(DF[,1])
    output=character()
    for(i in u){
      output<-append(output,paste0(paste0("'",i,"'"),":{",pastehier(DF[DF[,1]==i,-1]),
                           "}"))
    }
    return(paste0(output,collapse=","))
  }
}

pastehier(DF)
Jon Nagra
  • 1,538
  • 1
  • 16
  • 36

1 Answers1

1

I do not fully understand your request and maybe my solution is useless, but here is a try:

library(reshape2)
    prova <- dcast(DF, hie1 ~ ... )
     toJSON(prova, pretty = TRUE)
    [
      {
        "hie1": "Cl1",
        "Cl1op1": "/first.html",
        "Cl1op2": "/second.html"
      },
      {
        "hie1": "Cl2",
        "Clop1": "/third.html"
      }
    ] 

where:

> prova
  hie1      Cl1op1       Cl1op2       Clop1
1  Cl1 /first.html /second.html        <NA>
2  Cl2        <NA>         <NA> /third.html
SabDeM
  • 7,050
  • 2
  • 25
  • 38
  • My aim is to achieve the output I wrote in the second chunk. I start with a data.frame with i level 1 hierarchy, j_i level 2 hierarchy, k_{ji} level 3 hierarchy, etc. Sticking to the example the hierarchies are (i=2,j_1=2,j_2=1,k_ij=1 for all ij) and I want to transform it in {level1_1:{level2_1:level3_11,level2_2:level_3_12},level1_2:{...}}. I tried to state the issue in a simple way but it is not that simple :( Any editing help is appreciated. – Jon Nagra Nov 25 '15 at 18:07