How to Create a Data Frame from the Outputs of a Loop Functions

Hey team! I have been using the package zipcodeR to get a few mileage data points between zipcodes in USA using zip_distance and more recently wanted to pass each zipcode from list1 vs each zipcode in list2 to create a dataframe with all the outputs from the loop - i could get the loop to work, but have no idea how to have the sequential outputs on a df:

library(zipcodeR)
list1 <- c("45011","65322")
list2 <- c("65432","51545")

for (i in zip1) {
for (j in zip2){
print(zip_distance(i,j))
}
}

Instead of using loops, I would use expand.grid to make all the combinations and then the apply() function to iterate through the rows. In the example below, I used the paste() function because I don't have zipcodeR. I hope it gets the idea across.

 list1 <- c("45011","65322")
list2 <- c("65432","51545")
AllZips <- expand.grid(list1,list2)
AllZips
   Var1  Var2
1 45011 65432
2 65322 65432
3 45011 51545
4 65322 51545
AllZips$Output <- apply(AllZips, MARGIN = 1, function(Vec) paste(Vec[1],Vec[2], sep = "|"))
> AllZips
   Var1  Var2      Output
1 45011 65432 45011|65432
2 65322 65432 65322|65432
3 45011 51545 45011|51545
4 65322 51545 65322|51545
1 Like

It worked! Thanks!! :grinning:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.