Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 9th, 2012  |  syntax: None  |  size: 2.24 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Getting dataframe directly from JSON-file?
  2. # library(plyr)
  3. # library(RJSONIO)
  4. # lstJson <- fromJSON("JSON_test.json")        #This is the file I read
  5. # dput(lstJson)                                              #What I did to get the txtJson below, for the benefit of testing.
  6.  
  7. txtJson <- structure(list(version = "1.1", result = structure(list(warnings = structure(list(), class = "AsIs"), fields = list(structure(list(info = "", rpl = 15, name = "time", type = "timeperiod"), .Names = c("info", "rpl", "name", "type")), structure(list(info = "", name = "object", type = "string"), .Names = c("info", "name", "type")), structure(list(info = "Counter1", name = "Counter1", type = "int"), .Names = c("info", "name", "type")), structure(list( info = "Counter2", name = "Counter2", type = "int"), .Names = c("info", "name", "type"))), timeout = 180, name = NULL, data = list( list(list("2011-05-01 17:00", NULL), list("Total", NULL), list(8051, NULL), list(44, NULL)), list(list("2011-05-01 17:15", NULL), list("Total", NULL), list(8362, NULL), list( 66, NULL))), type = "AbcDataSet"), .Names = c("warnings", "fields", "timeout", "name", "data", "type"))), .Names = c("version", "result"))
  8.  
  9. dfJson <- ldply(txtJson, data.frame)
  10.        
  11. time  object  Counter1  Counter2  
  12. 2011-05-01 17:00  Total  8051  44  
  13. 2011-05-01 17:15  Total  8362  66
  14.        
  15. "Error in data.frame("2011-05-01 17:00", NULL, check.names = FALSE, stringsAsFactors = TRUE) :
  16.   arguments imply differing number of rows: 1, 0"
  17.        
  18. > sapply( txtJson$result$data, unlist )
  19.      [,1]               [,2]              
  20. [1,] "2011-05-01 17:00" "2011-05-01 17:15"
  21. [2,] "Total"            "Total"          
  22. [3,] "8051"             "8362"            
  23. [4,] "44"               "66"              
  24. > t(sapply( txtJson$result$data, unlist ))
  25.      [,1]               [,2]    [,3]   [,4]
  26. [1,] "2011-05-01 17:00" "Total" "8051" "44"
  27. [2,] "2011-05-01 17:15" "Total" "8362" "66"
  28. > as.data.frame(t(sapply( txtJson$result$data, unlist )) )
  29.                 V1    V2   V3 V4
  30. 1 2011-05-01 17:00 Total 8051 44
  31. 2 2011-05-01 17:15 Total 8362 66
  32.        
  33. data.frame(t(sapply( txtJson$result$data, unlist )) ,stringsAsFactors=FALSE)
  34.        
  35. > read.table(textConnection("2011-05-01 17:00"), sep=",", colClasses="POSIXct")
  36.                    V1
  37. 1 2011-05-01 17:00:00