Jodiug
Jodiug

Reputation: 6073

Convert nested list to dataframe in R

This question sounds like it has already been asked on SO, but I ask it anyway because the existing answers did not work for me and I'm not sure how better to phrase it, as I am new to R and don't entirely grasp the intricacies of its data types.

Time for a minimal example. I am looking for a transformation of target such that targetObject is exactly equal to referenceObject.

reference = '{"airport":[{"name":"brussels","loc":{"lat":"1","lon":"2"}}],"parking":[{"name":"P1"}]}'
target =    '{"airport":{"name":"brussels","loc":{"lat":"1","lon":"2"}},"parking":{"name":"P1"}}'

referenceObject = jsonlite::fromJSON(reference)$airport
x =               jsonlite::fromJSON(target)$airport

# Transformation
targetObject = do.call(rbind.data.frame, x)

# Currently prints FALSE, should become TRUE
results_same = identical(referenceObject, targetObject)
print(results_same)

I would expect this to be very simple in any language, but R seems to handle the nested loc lists very differently depending on the shape of the outer object airport.

Upvotes: 0

Views: 87

Answers (1)

Jodiug
Jodiug

Reputation: 6073

I managed to find a solution by serializing back to JSON. It's not elegant but at least it works.

# Transformation
targetObject = jsonlite::fromJSON(jsonlite::toJSON(list(x), auto_unbox = TRUE))

For now I will not mark this answer as correct because it's more of a workaround than an ideomatic solution.

Upvotes: 1

Related Questions