Search code examples
rggmapgeocode

String causes geocode to throw error


running this line of code

library(ggmap)
geocode(location="Somewhere in Nigeria Winning",source="dsk", output="more")

throws this error

Error in vapply(gc$results[[1]]$address_components, function(x) x[[nameToGrab]],  : values must be length 1, but FUN(X[[1]]) result is length 0

can someone shed some light on why this may be happening and what i can do to fix it? i know this seems like an odd question however this string showed up in a set of data to prune and seems to be breaking geocode.


Solution

  • just want to post an answer since i have located the problem, and anyone would like the workaround/want to know what to do. The issue is not with the DSK but with the ggmap code itself. If you run

    geocode(location="not a place in the slightest",source="dsk", output="more")
    

    then the library will fail gracefully and give you back the expected.

    geocode failed with status ZERO_RESULTS, location = "not a place in the slightest" 
    

    however with certain strings in the middle like the one above it fails less gracefully because DSK returns data but it isn't good data the issue is caused by the data that sits here in the resulting array (note for obvious reasons you cant get this using the more flag you need to use all).

    $results[[1]]$address_components[[1]]$long_name
    NULL
    
    $results[[1]]$address_components[[1]]$short_name
    NULL
    

    the code in the lib that parses this into the data frame with the "more" flag chokes here

    nameToGrab   <- `if`(nameType == "long", "long_name", "short_name")
    outputVals  <- vapply(gc$results[[1]]$address_components, function(x)  
    x[[nameToGrab]], character(1))
    outputNames <- vapply(gc$results[[1]]$address_components, function(x){ if(length(x$types) == 0) return("query")
          x$types[1]
        },
        character(1)
    )
    

    becasue both long_name and short_name are NULL the vapply is going to fail spectacularly.