I have a JSON file to be imported into R. Here is a section of the data:
{"data":[{"British Columbia":"BC","BC":"4.63"}, {"Alberta":"AB","AB":"4.15"}, {"Ontario":"ON","ON":"13.6"}]}
I need to turn this data into a dataframe, but the import is producing many NA values.
I tried the following:
library(jsonlite)
jsonData <- fromJSON("filepath")
jsonData
Output:
$data
British Columbia BC Alberta AB Ontario ON Manitoba MB Saskatchewan SK
1 BC 4.63 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
2 <NA> <NA> AB 4.15 <NA> <NA> <NA> <NA> <NA> <NA>
3 <NA> <NA> <NA> <NA> ON 13.6 <NA> <NA> <NA> <NA>
4 <NA> <NA> <NA> <NA> <NA> <NA> MB 1.28 <NA> <NA>
5 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> SK 1.1
It appears to be because of the single term "data" at the beginning of the JSON file. How can I avoid this issue?
Desired output:
British Columbia BC
BC 4.63
Alberta AB
AB 4.15
Ontario ON
ON 13.6
Manitoba MB
MB 1.28
Saskatchewan SK
SK 1.1
2
Answers
Given
x
shown in the Note at the end, usefromJSON
, extract the data portion, remove the NA’s and convert the types to the correct ones.giving
Note
In the call to jsonlite::fromJSON(…) add "simplifyVector = FALSE" so that the data is returned as a list.
Then unlist and convert to a data.frame