1

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.

Chris Claxton
  • 413
  • 6
  • 11
  • What would be your expected output? As the error message clearly says `x` and `y` has different number of rows. – Ronak Shah Feb 16 '17 at 12:24
  • For each x, I think OP wants a list in y. – Roman Luštrik Feb 16 '17 at 12:24
  • Thanks, Ronak, good question. If I start with the data frame (which I got using JSON parsing), why can't I rebuild the data frame using the original data frame's elements? – Chris Claxton Feb 16 '17 at 12:29
  • You're probably after this. http://stackoverflow.com/questions/15980281/storing-a-list-within-a-data-frame-element-in-r – Roman Luštrik Feb 16 '17 at 12:30
  • For a data frame in R the number of rows has to be equal as it works similar to a matrix. May I ask why do you need a data frame rather than a list? Edit: Check this as well http://stackoverflow.com/questions/7196450/create-a-data-frame-of-unequal-lengths. – FilipeTeixeira Feb 16 '17 at 12:23
  • That's a good question. In the small example I've pasted, I can use a list, but it's part of a bigger project where the result needs to be a data frame. I'm just perplexed as to why I can get a data frame with the structure shown (using the jsonlite package), but I can't recreate the data frame. – Chris Claxton Feb 16 '17 at 12:27

1 Answers1

4

You can get the structure you want via

data.frame(x = data$x, y = I(data$y))

  x       y
1 3 3, 4, 5
2 6 6, 7, 8

See also Create a data.frame where a column is a list.

Community
  • 1
  • 1
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197