Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply function to every row in R

I have a dataframe with two columns, zip and CSZip. I am trying to apply a function to each row using:

dist <- apply(vf, 1, zip_distance(zip, CSZip, lonlat = TRUE, units = "meters"))

But I get this error:
Error in as.character(zipcode_a) :
cannot coerce type ‘closure’ to vector of type ‘character’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

zip_distance is from the ZipCodeR package.

This is what 5 rows of vf looks like:

zip CSZip
91723 90048
90814 90048
91604 90048
90805 90048
90255 90048

>Solution :

The ZipcodeR is has some funky behavior.
Sometimes it is just easier to use a for loop:

library(zipcodeR)

vf <- read.table(header=TRUE, text="zip CSZip
91723   90048
90814   90048
91604   90048
90805   90048
90255   90048")


for(i in 1:nrow(vf)) {
   vf$dist[i] <- zip_distance(vf$zip[i], vf$CSZip[i], lonlat = TRUE, units = "meters")$distance
}
vf
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading