Suppose I have a JSON file that contains this:
[
{
"x": 3,
"y": [3,4,5]
},
{
"x": 6,
"y": [6,7,8]
}
]
If this is loaded using the fromJSON
function in the jsonlite
R package as follows:
# Read the JSON data
library(jsonlite)
data <- fromJSON('[{"x":3,"y":[3,4,5]},{"x":6,"y":[6,7,8]}]')
then the x
and y
fields can be accessed like this:
> data$x
[1] 3 6
> data$y
[[1]]
[1] 3 4 5
[[2]]
[1] 6 7 8
Suppose instead of already having the data frame, I try to build it as follows:
> x2 <- data$x
> y2 <- data$y
> df <- data.frame(x = x2, y = y2)
Error in data.frame(x = x2, y = y2) :
arguments imply differing number of rows: 2, 3
we can see that the data frame can't be reconstructed this way. How can I build the data frame that contains lists?
Sorry, for clarity:
> data <- fromJSON('[{"x":3,"y":[3,4,5]},{"x":6,"y":[6,7,8]}]')
> class(data)
[1] "data.frame"
I can parse JSON to build a data frame, but the method I used above can't build the data frame. I'm fairly new to R, so I'm probably doing something silly.