rdata.tablerjsoniojsonlite

Using data.table and RJSONIO / jsonlite - results are transposed


I have implemented a wrapper library part of rstudio's htmlwidgets that renders a pivot table. The package is here.

The package works well with data.tables and data.frame (as it should!). For example it works with iris. On the other hand if I try to convert iris to data.table my package (actually htmlwidgets - which internally uses RJSONIO) throws an error.

I know that it seems convoluted, but you can sort of reproduce the error just checking the difference between the following codes:

library(data.table)
library(RJSONIO)
data.table(fromJSON(toJSON(data.table(iris))))

The result is different from the dear iris dataset:

                                           V1
1:                   5.1,4.9,4.7,4.6,5.0,5.4,
2:                   3.5,3.0,3.2,3.1,3.6,3.9,
3:                   1.4,1.4,1.3,1.5,1.4,1.7,
4:                   0.2,0.2,0.2,0.2,0.2,0.4,
5: setosa,setosa,setosa,setosa,setosa,setosa,

On the other hand jsonlite is able to re-build iris properly (just remember to detach RJSONIO before running the code):

    library(data.table)
    library(jsonlite)
    data.table(fromJSON(toJSON(data.table(iris))))

     Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
  1:          5.1         3.5          1.4         0.2    setosa
  2:          4.9         3.0          1.4         0.2    setosa
  3:          4.7         3.2          1.3         0.2    setosa
  4:          4.6         3.1          1.5         0.2    setosa
  5:          5.0         3.6          1.4         0.2    setosa

I am not sure if the problems lies with data.table or RJSONIO...


Solution

  • This is not related to json.
    RJSONIO::fromJSON returns list while jsonlite::fromJSON returns data.frame.
    It is related to data.table call on list which is different than call on data.frame, but still behave as expected.
    Try as.data.table instead of data.table in the outer call.

    as.data.table(fromJSON(toJSON(data.table(iris))))
    

    This was already discussed on data.table github. I've reply to your issue the reference to the discussion.