2

I would like to have a list of matrices within R imported from a json file using jsonlite.

A <- matrix(rnorm(100),10,10)
B <- matrix(rnorm(100),10,10)
C <- matrix(rnorm(100),10,10)
l <- list(A,B,C)
import_l <- fromJSON(toJSON(l),simplifyMatrix = FALSE)

the above code doesnt work since it is R internally a list of list of numerics. However, I would like to have my list of A,B,C back, i.e. l. Is there a way to achieve getting back the correct list of matrices using jsonlite?

math
  • 1,868
  • 4
  • 26
  • 60

1 Answers1

1

The issue here is that a column matrix and an unnamed list look the same if converted to JSON:

toJSON(list(1, 2, 3))
## [[1],[2],[3]] 
toJSON(matrix(c(1, 2, 3), ncol = 1))
## [[1],[2],[3]]

However, a named list looks different:

toJSON(list(A = 1, B = 2, C = 3))
## {"A":[1],"B":[2],"C":[3]} 

If you use a named list in your example, fromJSON() does indeed reproduce the original list:

l <- list(A = A, B = B, C = C)
all.equal(fromJSON(toJSON(l)), l, tol = 1e-4)
## [1] TRUE

If this is not possible - for example because you don't create the JSON file yourself, but get it as an input - you can also convert the result you get with fromJSON():

l <- list(A, B, C)
import_l <- fromJSON(toJSON(l))
l2 <- lapply(1:3, function(i) import_l[i, , ])
all.equal(l2, l, tol = 1e-4)
## [1] TRUE
Stibu
  • 15,166
  • 6
  • 57
  • 71