R code to iterate through dataframe rows for google maps distance queries
<p>I'm looking for some assistance in writing some R code to iterate through rows in a dataframe and pass the values in each row to a function and print the output either to an excel file, txt file or just in the console.</p>

<p>The purpose of this is to automate a bunch of distance/time queries (several hundred) to google maps using the function found at this website: <a href="http://www.nfactorialanalytics.com/r-vignette-for-the-week-finding-time-distance-between-two-places/" rel="nofollow noreferrer">http://www.nfactorialanalytics.com/r-vignette-for-the-week-finding-time-distance-between-two-places/</a></p>

<p>The function on that website is as follows:</p>

<pre><code>library(XML)
library(RCurl)
distance2Points &lt;- function(origin,destination){
 results &lt;- list();
 xml.url &lt;- paste0('http://maps.googleapis.com/maps/api/distancematrix/xml?origins=',origin,'&amp;destinations=',destination,'&amp;mode=driving&amp;sensor=false')
 xmlfile &lt;- xmlParse(getURL(xml.url))
 dist &lt;- xmlValue(xmlChildren(xpathApply(xmlfile,"//distance")[[1]])$value)
 time &lt;- xmlValue(xmlChildren(xpathApply(xmlfile,"//duration")[[1]])$value)
 distance &lt;- as.numeric(sub(" km","",dist))
 time &lt;- as.numeric(time)/60
 distance &lt;- distance/1000
 results[['time']] &lt;- time
 results[['dist']] &lt;- distance
 return(results)
}
</code></pre>

<p>The dataframe will contain two columns: origin postal code and destination postal code (Canada, eh?). I'm a beginner R programmer, so I know how to use read.table to load a txt file into a dataframe. I'm just not sure how iterate through the dataframe, each time passing values to the distance2Points function and executing. I think this can be done using either a for loop or one of the apply calls?</p>

<p>Thanks for the help!</p>

<p>edit:</p>

<p>To keep it simple lets assume I want to transform these two vectors into a dataframe</p>

<pre><code>&gt; a &lt;- c("L5B4P2","L5B4P2")
&gt; b &lt;- c("M5E1E5", "A2N1T3")
&gt; postcodetest &lt;- data.frame(a,b)
&gt; postcodetest
       a      b
1 L5B4P2 M5E1E5
2 L5B4P2 A2N1T3
</code></pre>

<p>How should I go about iterating over these two rows to return both distances and times from the distance2Points function?</p>