1

I got a list (from a JSON extracted with rjson) which defines in a bizarre way the different values of an element for given x and y values (like to draw a graph line). What I look for is to produce a data.frame which contains only the values, with the possible values of x and y in row names and col headers.

In other words, I try to obtain this kind of data frame:

    y1  y2
x1 v11 v12
x2 v21 v22

And the list I got as entry is like:

[
  [
    x1,
    [
      [y1, v11],
      [y2, v12]
    ]
  ],
  [
    x2,
    [
      [y1, v21],
      [y2, v22]
    ]
  ]
]

It is a list of lists; each inner list contains two elements: one x value and a list of list. Those most-inner lists have two elements, a y value and a v value, which represents the value of the object for the x of its parent and for the y with it.

I hope my explanation is not too confuse. I have made some unsuccessful attemps with ldply or matrix(unlist(... I look for a way to transform my list without having to pick one by one each value in a double for loop.

Thanks for reading and for any help you can provide.

[EDIT]

Here is the dput of my data:

list(list(20, list(c(1, 224), c(3, 330), c(5, 436), c(10, 701
), c(20, 1231), c(30, 1231))), list(10, list(c(1, 154), c(3, 
207), c(5, 366), c(10, 631), c(20, 631), c(30, 631))), list(5, 
list(c(1, 119), c(3, 225), c(5, 331), c(10, 331), c(20, 331
), c(30, 331))), list(1, list(c(1, 91), c(3, 91), c(5, 91
), c(10, 91), c(20, 91), c(30, 91))))

In this example, 20, 10, 5, 3, 1 are supposed to be the future x of the dataframe and 1, 3, 5, 10, 20, 30 the future y. The rest are values of the object.

Erkethan
  • 15
  • 3

1 Answers1

2

The package jsonliteis able to simplify data structures when converting from JSON to R. I am not sure if rjson offers something similar. Here I am using this to round trip from R to JSON and back, giving me a matrix for y_i and v_ij:

foo <- list(list(20, list(c(1, 224), c(3, 330), c(5, 436), c(10, 701), c(20, 1231), c(30, 1231))), 
            list(10, list(c(1, 154), c(3, 207), c(5, 366), c(10, 631), c(20, 631), c(30, 631))), 
            list(5, list(c(1, 119), c(3, 225), c(5, 331), c(10, 331), c(20, 331), c(30, 331))), 
            list(1, list(c(1, 91), c(3, 91), c(5, 91), c(10, 91), c(20, 91), c(30, 91))))
bar <- jsonlite::fromJSON(jsonlite::toJSON(foo))
baz <- Reduce(rbind,lapply(bar, function(x) t(x[[2]])[2, ]))
colnames(baz) <- bar[[1]][[2]][,1]
rownames(baz) <- unlist(lapply(bar, function(x) x[[1]]))
baz
#>      1   3   5  10   20   30
#> 20 224 330 436 701 1231 1231
#> 10 154 207 366 631  631  631
#> 5  119 225 331 331  331  331
#> 1   91  91  91  91   91   91
Ralf Stubner
  • 26,263
  • 3
  • 40
  • 75
  • Indeed, works like a charm with `jsonlite` imported data structure! Double thanks for your elegant structure conversion as well, it's really great. – Erkethan Feb 23 '18 at 08:30