I've created a data.table in that has 6 columns. My data.table has a columns compairing two locations: Location 1 and Location 2. I'm trying to use the distm function to calculate the distance between the locations on each row, creating a 7th column. The distm package in the geosphere package requires two different vectors for each lat/long combo to be calculated against. My code below does not work, so I'm trying to figure out how to provide vectors to the function.
LOC_1_ID LOC1_LAT_CORD LOC1_LONG_CORD LOC_2_ID LOC2_LAT_CORD LOC2_LONG_CORD
1 35.68440 -80.48090 70624 34.86752 -82.46632
6 35.49770 -80.62870 70624 34.86752 -82.46632
10 35.66042 -80.50053 70624 34.86752 -82.46632
Assuming res holds the data.table the below code does not work.
res[,DISTANCE := distm(c(LOC1_LAT_CORD, LOC1_LONG_CORD),c(LOC2_LAT_CORD, LOC2_LONG_CORD), fun=distHaversine)*0.000621371]
If I were to pull out each vector the function works fine.
loc1 <- res[LOC1_ID == 1,.(LOC1_LAT_CORD, LOC1_LONG_CORD)]
loc2 <- res[LOC2_ID==70624,.(LOC2_LAT_CORD, LOC2_LONG_CORD)]
distm(loc1, loc2, fun=distHaversine)
Really, my question is how to apply functions to select columns within a data.table when that function requires vectors as parameters.