Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a function to each row in a data.frame and append the result to the data.frame in R

It seems like I should either know how to do this or at least find the answer here or elsewhere. Unfortunately neither is working.

I have a data frame of customers where one column is their id and another column is their full address. I want to add 3 columns for each row with the lat, long and county code from a geocode lookup.

That data frame looks like

customer_id       fulladdress
     1            123 Main St., Anywhere, FL
     2            321 Oak St., Thisplace, CA

I created a geocode function that takes the full address and returns a data frame with lat, long and county columns.

How can I apply my geocode function to each row of the data frame and append the results as 3 columns into the existing data frame so that it looks like this:

customer_id       fulladdress                      lat        long     county
     1            123 Main St., Anywhere, FL     33.2345    -92.3333   43754
     2            321 Oak St., Thisplace, CA     25.3333    -120.333   32960

I've tried playing with apply and ddply, but I can't seem to figure out what either one is doing. I tried this with ddply but all it does is give me back the original data frame.

ddply(customers[1:3,], .(fulladdress), function(x) { geocode(x$fulladdress)})

Thanks for the help.

like image 919
Dave Kincaid Avatar asked Nov 14 '11 17:11

Dave Kincaid


1 Answers

Thanks for putting me on the right track. Here is what finally worked:

cbind(customers, t(sapply(customers$fulladdress,geocode, USE.NAMES=F))) 
like image 185
Dave Kincaid Avatar answered Oct 22 '22 07:10

Dave Kincaid