Reputation: 8444
I have the dataframe dtshp
id=c(0,0)
long<-c(140.9619,140.9626 )
lat<-c(-35.79979,-35.77946)
order<-c(1,2)
hole<-c(FALSE,FALSE)
piece<-c(1,1)
group<-c(0.1,0.1)
dtshp<-data.frame(id,long,lat,order,hole,piece,group)
and the dataframe dt
Town<-c("WATSONIA","NORTH MELBOURNE")
lat<-c(-35.79979,-35.77946)
long<-c(140.9619,140.9626)
pop<-c(1232131,213312)
dt<-data.frame(Town,lat,long,pop)
dt["id"] <- NA
How could I fill the values of dt$id
with the values of dtshp$id
when they have common pair of lat
and long
?
Upvotes: 0
Views: 98
Reputation: 1263
library(dplyr)
dt %>%
left_join(dtshp, by = c("Longitude" = "long", "Latitude" = "lat"))
This will create columns in the merged data frame for id.x
and id.y
, since both data frames have a column for id
. You could remove it from the dt
data frame first, or use mutate
/transmute
/select
after joining to choose the columns you want.
Upvotes: 2
Reputation: 1131
dt$id <- dtshp[dtshp$long == dt$long & dtshp$lat == dt$lat,]$id
which gives:
Town lat long pop id
WATSONIA -35.79979 140.9619 1232131 0
NORTH MELBOURNE -35.77946 140.9626 213312 0
Upvotes: 1