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.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Michal
  • 1,863
  • 7
  • 30
  • 50
  • 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. – Thomas Jun 24 '14 at 18:09
  • I do realize that there is a problem but without an else clause, the code failed before. – Michal Jun 24 '14 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. – Michal Jun 24 '14 at 18:11
  • 1
    I guess you would gain speed from something like `zipcode[c("latitude", "longitude")][match(Summer2013$zipcode, zipcode$zip), ]` – alexis_laz Jun 24 '14 at 18:13
  • 1
    Take a look at this question and answer: http://stackoverflow.com/questions/15303283/how-to-do-vlookup-and-fill-down-like-in-excel-in-r/15307710#15307710 – Thomas Jun 24 '14 at 18:13
  • Hi, Take a bit of time and read the tag excerpt before tagging. [tag:dataframes] is for pandas, whereas you need [tag:data.frame] here. Be careful the next time. See this meta post. [Warn \[r\] users from adding \[dataframes\] tag instead of \[data.frame\] tag](http://meta.stackoverflow.com/q/318933) – Bhargav Rao Mar 14 '16 at 13:40

1 Answers1

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.

rrs
  • 9,615
  • 4
  • 28
  • 38