2016-04-15 8 views
0

Ich möchte Json-Datei von R data.frame als Eingabe für DataTables (link) erstellen.Json für DataTables von data.frame unter Verwendung von R

df <- data.frame(RowNames <- c("FirstCol","SecondCol","ThirdCol","FourthCol"), 
           FirstCol <- c(0.1,0,0,0.28), 
           SecondCol <- c(0,0,0.1,0), 
           ThirdCol <- c(0,0,0,0.3), 
           FourthCol <- c(0.28,0,0,0.7)) 
names(df) <- c("RowNames", "FirstCol", "SecondCol", "ThirdCol", "FourthCol") 

Wunsch ausgegeben werden soll:

{ 
    "columns": [ 
    {"title":"Json for table"}, 
    { "title": "FirstCol"}, 
    { "title": "SecondCol"}, 
    { "title": "ThirdCol"}, 
    { "title": "FourthCol"}], 
"data": [ 
    ["FirstCol", "0.1", "0", "0", "0.28"], 
    ["SecondCol", "0", "0", "0.1", "0"], 
    ["ThirdCol", "0", "0", "0", "0.3"], 
    ["FourthCol", "0.28", "0", "0", "0.7"]] 
} 

Sie eine Idee haben Sie, wie kann ich das auf einfachste Weise? Vielen Dank für Ihre Hilfe.

+0

Sorry, I‘ Die aktualisierte Eingabedatei. – SmithiM

+0

Sind Sie sicher, dass die Spaltennamen auch mit den Daten angegeben werden sollen? – akrun

+0

Ja, sollte es nach jQuery DataTables dort sein. Wenn ich {"title": "Json for table"} lösche, werden alle Spalten nach links verschoben. – SmithiM

Antwort

0

Ich schrieb diese verrückte Funktion JSON von einer rekursiven Listenstruktur zu erzeugen:

rlistToJSON <- function(node,indent=0L) { 
    if (is.na(indent)) { 
     LF <- tab0 <- tab1 <- ''; 
    } else { 
     LF <- '\n'; 
     tab0 <- paste(collapse='',rep(' ',indent)); 
     tab1 <- paste(collapse='',rep(' ',indent+1L)); 
    }; ## end if 
    res <- if (is.list(node)) { ## array or hash 
     if (is.null(names(node))) { ## array 
      if (length(node)==0L) { ## empty array 
       '[]' 
      } else { ## non-empty array 
       paste0(
        '[',LF, 
        paste(
         collapse=paste0(',',LF), 
         sapply(seq_along(node),function(i) 
          paste0(
           tab1, 
           rlistToJSON(node[[i]],indent+1L) 
          ) 
         ) 
        ), 
        LF,tab0,']' 
       ) 
      }; ## end if 
     } else { ## hash 
      if (length(node)==0L) { ## empty hash 
       '{}' 
      } else { ## non-empty hash 
       paste0(
        '{',LF, 
        paste(
         collapse=paste0(',',LF), 
         sapply(seq_along(node),function(i) 
          paste0(
           tab1, 
           '"',gsub('(["\\\\])','\\\\\\1',names(node)[i]),'":', 
           rlistToJSON(node[[i]],indent+1L) 
          ) 
         ) 
        ), 
        LF,tab0,'}' 
       ) 
      }; ## end if 
     }; ## end if 
    } else if (is.null(node)) { ## null 
     'null'; 
    } else { ## primitive vector 
     content <- ifelse(is.na(node),'null',if (is.logical(node)) { ## boolean 
      c('false','true')[node+1L] 
     } else if (is.numeric(node)) { ## numeric 
      node 
     } else if (is.character(node)) { ## string 
      paste0('"',gsub('(["\\\\])','\\\\\\1',node),'"') 
     } else stop(paste0('invalid node type: ',typeof(node),'.'))); ## invalid 
     if (!is.null(names(node))) 
      content <- paste0('"',gsub('(["\\\\])','\\\\\\1',names(node)),'":',content); 
     content <- paste(collapse=',',content); 
     if (!is.null(names(node))) { 
      paste0('{',content,'}') 
     } else if (length(node)==1L) { 
      content 
     } else { 
      paste0('[',content,']'); 
     }; ## end if 
    }; ## end if 
    if (!is.na(indent) && indent==0L) paste0(res,LF) else res; 
}; ## end rlistToJSON() 

Zufallstests:

cat(rlistToJSON(list())); 
## [] 
cat(rlistToJSON(setNames(list(),character()))); 
## {} 
cat(rlistToJSON(3)); 
## 3 
cat(rlistToJSON(3:4)); 
## [3,4] 
cat(rlistToJSON(list(3))); 
## [ 
## 3 
## ] 
cat(rlistToJSON(list(3:4,5))); 
## [ 
## [3,4], 
## 5 
## ] 
cat(rlistToJSON(list(a=3,b=4))); 
## { 
## "a":3, 
## "b":4 
## } 
cat(rlistToJSON(list('a"\\b'))); 
## [ 
## "a\"\\b" 
## ] 
cat(rlistToJSON(list(letters[1:10],LETTERS[1:10]))); 
## [ 
## ["a","b","c","d","e","f","g","h","i","j"], 
## ["A","B","C","D","E","F","G","H","I","J"] 
## ] 
cat(rlistToJSON(list(c(T,F),list(c(4.56,1234.34),x=c(a=45,b=5))))); 
## [ 
## [true,false], 
## { 
##  "":[4.56,1234.34], 
##  "x":{"a":45,"b":5} 
## } 
## ] 
cat(rlistToJSON(list(NULL,NULL,c(3,NA,4),'a'))); 
## [ 
## null, 
## null, 
## [3,null,4], 
## "a" 
## ] 
cat(rlistToJSON(list(NULL,NULL,c(3,NA,4),'a'),NA),'\n'); 
## [null,null,[3,null,4],"a"] 
cat(rlistToJSON(c('a','b"',NA))); 
## ["a","b\"",null] 
cat(rlistToJSON(c(a='a',b='b"',c=NA))); 
## {"a":"a","b":"b\"","c":null} 

Für Ihre Daten:

cat(rlistToJSON(list(
    columns=unname(lapply(c('Json for table',names(df)[-1L]),function(x) c(title=x))), 
    data=unname(Map(c,names(df)[-1L],df[-1L])) 
))); 
## { 
## "columns":[ 
##  {"title":"Json for table"}, 
##  {"title":"FirstCol"}, 
##  {"title":"SecondCol"}, 
##  {"title":"ThirdCol"}, 
##  {"title":"FourthCol"} 
## ], 
## "data":[ 
##  ["FirstCol","0.1","0","0","0.28"], 
##  ["SecondCol","0","0","0.1","0"], 
##  ["ThirdCol","0","0","0","0.3"], 
##  ["FourthCol","0.28","0","0","0.7"] 
## ] 
## } 
+1

Cool, vielen Dank !! – SmithiM

Verwandte Themen