2

I have a data frame with temperatures from summer 2013. I would like to map the temperatures geographically using their latitude and longitude based on this example. I have a dataset with the temperatures and zip codes and I would like to add a column with the appropriate lat and long to my original data frame.

I wrote a nested loop that works but is terribly inefficient:

for (i in 1:length(Summer2013$zipcode)) {
  for (j in 1:length(zipcode$zip)) {
    col[i] <- if (Summer2013$zipcode[i] == zipcode$zip[j]) {
      zipcode$longitude[j] 
    } else {0}
  }
}

(so far I thought I'd just try doing the long and when I figured out something better, I was going to do the lat as well)

I know that R is able to perform loops using column assignments but I was afraid of not getting an expected result so wanted to err on the side of caution.

6
  • You may want ifelse, but the code you're showing here will overwrite values in col repeatedly, so it's not clear what you're actually trying to do. Commented Jun 24, 2014 at 18:09
  • I do realize that there is a problem but without an else clause, the code failed before. Commented Jun 24, 2014 at 18:10
  • I am trying to add two columns to my data frame - one with long based on zipcode and one with lat based on zipcode. This would be equivalent to a vlookup in excel. Commented Jun 24, 2014 at 18:11
  • 1
    I guess you would gain speed from something like zipcode[c("latitude", "longitude")][match(Summer2013$zipcode, zipcode$zip), ] Commented Jun 24, 2014 at 18:13
  • 1
    Take a look at this question and answer: stackoverflow.com/questions/15303283/… Commented Jun 24, 2014 at 18:13

1 Answer 1

1

you want to merge the datasets:

merge(Summer2013, zipcode, by.x="zipcode", by.y="zip", all.x=TRUE)

this is a left join and will return NA for zipcodes it can't find in the zipcode data frame.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.