Search code examples
rjsonr-leaflet

Iterate through nested objects in an array


I am trying to call upon the latitude and longitude of objects in an array in R, in conjunction with leaflet.

dMVStations <- fromJSON(file = "stations.json")
# "stations.json" is an array of 88 objects with 36 attributes each.
# two of those attributes are latitude and longitude.

...
# setting up the leaflet map
...

leafletProxy("map", data = dMVStations) %>%
  addCircles(
    lng =~ dMVStations$[[1]...[88]]$longitude,
    lat =~ dMVStations$[[1]...[88]]$latitude,
    ...
  )

How do I point to the latitude and longitude for each object within dMVStations?

str(dMVStations) returns:

name: dMVStations
type: list[88]
value: 'List of length 88'

each of those 88 objects is

named by the index [[1]...[88]]
has type: list[36]
has value: 'List of length 36'

Solution

  • As you can see from str dMVStations contains 88 entries. Each entry is a list (vector) with 36 values, just as you described your JSON file "88 objects with 36 attributes each".

    Let's say latitude and longitude are attributes 5 and 9 respectively in the list of attributes read from JSON file. To access them for location i you would use syntax like this:

    lat <- dMVStations[[i]][5]
    lon <- dMVStations[[i]][9]
    

    If columns are named you should be able to access them using something like this:

    lat <- dMVStations$latitude[i]
    lon <- dMVStations$longitude[i]