Search code examples
pythonrparsingmatrix

How to read scalar, vector and matrix information in string format resembling Python syntax in R?


I have strings that contain scalars, vectors, and matrices, e.g.

"[0,1],[[1,2],[3,4]],42"

And following the same example, that input in R should give me this:

[[1]]
[1] 0 1

[[2]]
     [,1] [,2]
[1,]    1    3
[2,]    2    4

[[3]]
[1] 42

So the notation is similar to that of Python where matrices are actually lists of lists.

Should I just write a parser for this, or has somebody already done that or is there a simple and neat trick to achieve this with no or only a little effort?


Solution

  • x <- "[0,1],[[1,2],[3,4]],42"
    xx <- paste0("[", x, "]")
    jsonlite::fromJSON(xx)