I have a JSON file that looks as such:
library(jsonlite)
test_file <- jsonlite::fromJSON("https://raw.githubusercontent.com/datacfb123/testdata/main/test_file_lp.json")
If you open up test_file
in R, you can see it looks as such:
The problem arises from the latestPosts
data where some columns contain the data I need, but others don’t. If you open up the subdata for username3, you will see two columns titled locationName
and locationId
, like screen shot below:
But the nested data for username1
and username2
does not contain those fields, which is fine. username1
has nested data under latestPosts
that doesn’t have what we need, while username2
has no data.
I am trying to write a script that captures the two location columns from whoever has them, while still keeping the original three columns that are in all of them. So the final dataframe would look like this:
2
Answers
You can use
tidyr::unnest()
to get all columns from all dataframes. Then do a groupeddplyr::summarize()
to keep all non-NA
values for your columns of interest, or else a singleNA
row if there are no non-NA
values for a group.One option is a simple helper function that can be applied using
map()
Output: