title: R - retrieve correct objects from google maps API and save to data frame
body: <p>for a work project I'm trying to weight bulk twitter data by geographic distribution of the tweets. Currently, I'm planning to achieve this by running the <code>location</code> information provided in most tweets I've collected through the Google Maps API and retrieving detailed information on this location as far as it's available, i.e. <strong>town, county, state, country, longditude, latitude</strong>. </p>
  
  <p>I've adapted some R code I found on github, <a href="https://gist.github.com/josecarlosgonz/6417633" rel="nofollow">https://gist.github.com/josecarlosgonz/6417633</a>, and it works pretty well, returning the desired data points into an R character vector. However, as I'll be doing this for several millions of locations, I want the data saved in a data frame which I can then match up with the tweet dataframe so as to facilitate weighting. Hence, I went ahead and modified Jose's code slightly: </p>
  
  <pre><code>library(RJSONIO)
  library(plyr)
  library(RCurl)
  
  # This is the function that transforms an "address" string into a URL readable by the G maps API
  
  url &lt;- function(address, return.call = "json", sensor = "false"){
    root &lt;- "http://maps.google.com/maps/api/geocode/"
    u &lt;- paste(root, return.call, "?address=", address, "&amp;sensor=", sensor, sep = "")
    return(URLencode(u))
  }
  
  # This function returns the data provided by the API
  # When the request is ambiguous, e.g. "Portland", "Manchester" or "Frankfurt", it seems that the API returns the "best" match
  # first, i.e. Portland, Oregon, Manchester, UK and Frankfurt am Main, Germany.
  # The below set-up currently only works with U.S. localities, as the 'county' and 'state' elements are sorted at different points
  # in the list for other countries. 
  
  geoCode &lt;- function(address,verbose=FALSE){
    if(verbose) cat(address,"\n")
    u &lt;- url(address)
    doc &lt;- getURL(u)
    x &lt;- fromJSON(doc,simplify = FALSE)
    if(x$status=="OK") {
      if(exists(x$results[[1]]$address_components[[1]]$long_name)){
        town &lt;- x$results[[1]]$address_components[[1]]$long_name
      } else {
      town &lt;- NA
      }
      if(exists(x$results[[1]]$address_components[[2]]$long_name)){
        county &lt;- x$results[[1]]$address_components[[2]]$long_name
      } else {
        county &lt;- NA
      }
      if(exists(x$results[[1]]$address_components[[3]]$long_name)){
        state &lt;- x$results[[1]]$address_components[[3]]$long_name
      } else {
        state &lt;- NA
      }
      if(exists(x$results[[1]]$address_components[[3]]$short_name)){
        state_code &lt;- x$results[[1]]$address_components[[3]]$short_name
      } else {
        state_code &lt;- NA
      }
      if(exists(x$results[[1]]$geometry$location$lat)){
        lat &lt;- x$results[[1]]$geometry$location$lat
      } else {
        lat &lt;- NA
      }
      if(exists(x$results[[1]]$geometry$location$lng)){
        lng &lt;- x$results[[1]]$geometry$location$lng
      } else {
        lng &lt;- NA
      }
      if(exists(x$results[[1]]$geometry$location_type)){
        location_type &lt;- x$results[[1]]$geometry$location_type
      } else {
        location_type &lt;- NA
      }
      if(exists(x$results[[1]]$formatted_address)){
        formatted_address &lt;- x$results[[1]]$formatted_address
      } else {
        formatted_address &lt;- NA
      }
      return(c(town, county, state, state_code, lat, lng, location_type, formatted_address))
      Sys.sleep(0.5)
    } else {
      return(c(NA,NA,NA,NA,NA,NA,NA,NA))
    }
  }
  </code></pre>
  
  <p>However, when trialling this with a trivial example, I encounter several errors that I can't account for. It seems to me that, based on the level of detail provided in the string that's being fed into the G maps API, it returns different types of data at different points in the list, which is obviously bad if I want a dataset where all the counties, or long/lat data are listed in the correct columns. So, anyway, I created an arbitrary character vector with 'address' data comparable to what would be found in my tweet dataset: </p>
  
  <pre><code>pacific_northwest &lt;- c('Vancouver', 'Seattle', 'Olympia', 'Redmond', 'Eugene', 'Portland', 'Tacoma', 'Whistler')
  </code></pre>
  
  <p>and then an empty data frame that google maps' output could be fed into</p>
  
  <pre><code>location_data.df &lt;- data.frame(town=character(),
                             county=character(), 
                             state=character(), 
                             state_code=character(),
                             lat=character(),
                             lng=character(),
                             location_type=character(),
                             formatted_address=character(),
                             stringsAsFactors = FALSE) 
  </code></pre>
  
  <p>And finally, I wrote a simple loop that was supposed to add the output to this data.frame:</p>
  
  <pre><code>for (i in pacific_northwest){
    readout &lt;- geoCode(pacific_northwest[i])
    location_data.df[nrow(location_data.df) + 1, ] &lt;- readout
    rm(readout)
  }
  </code></pre>
  
  <p>Anyway - this doesn't work, I encounter loads of errors, even with the more or less unambiguous addresses provided in <code>pacific_northwest</code>, such as: <code>Error in x$results[[1]]$address_components[[2]] : subscript out of bounds</code> </p>
  
  <p>What to do? Any help would be greatly appreciated! Thanks in advance. </p>