Reputation: 1905
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.
Upvotes: 2
Views: 270
Reputation: 9903
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.
Upvotes: 1