I want to calculate the distance between lat1, lon1 and a reference point (52.92343, 5.04127). I want to this for every row in my dataset, so the distance will be calculated with the reference in every row. That means I will create a new column with the distance in km. I can imagine you will have to use some kind of loop function, but so far I have not figured out how to accomplish this. I think I will have to use the packages geodist
or geosphere
, but unfortunately was not successful. How can I calculate these distances?
structure(list(Day = c("26", "05", "17", "18", "19", "19"), Month = c("07",
"08", "08", "08", "08", "08"), Year = c("2021", "2021", "2021",
"2021", "2021", "2021"), Location.Receiver = c("Den Oever Ijsselmeer",
"Medemblik Ijsselmeer, gemaal", "Den Oever Ijsselmeer", "Den Oever Ijsselmeer",
"Den Oever Ijsselmeer", "Den Oever Ijsselmeer"), Transmitter = c("A69-1602-59776",
"A69-1602-59777", "A69-1602-59776", "A69-1602-59776", "A69-1602-59769",
"A69-1602-59776"), Batch.location = c("Den Oever", "Den Oever",
"Den Oever", "Den Oever", "Den Oever", "Den Oever"), BatchNr = c(8,
9, 8, 8, 1, 8), Latitude = c(52.92343, 52.76098, 52.92343, 52.92343,
52.92343, 52.92343), Longitude = c(5.04127, 5.12172, 5.04127,
5.04127, 5.04127, 5.04127), Date = structure(c(18834, 18844,
18856, 18857, 18858, 18858), class = "Date")), row.names = c(1095729L,
1180267L, 1072657L, 1092667L, 716601L, 1077415L), class = "data.frame")
CodePudding user response:
No need to loop, you can just calculate the distance between entries in an array of coordinates in x
and a single point in y
using geodist
. Just passing in the coordinates as lon/lat explicitly and saving back as a numeric vector to Distance
rather than as the original matrix output.
library(geodist)
df$Distance <- as.numeric(geodist(df[,9:8], c(5.04127, 52.92343)))
#> object has no named columns; assuming order is lon then lat
df$Distance
#> [1] 0.00 18843.92 0.00 0.00 0.00 0.00
CodePudding user response:
Please find an alternative solution (cf reprex below) using the sf
and units
library
Reprex
- Code
library(sf)
library(units)
# Convert the df into 'sf' object
df_sf <- df %>%
st_as_sf(coords = c("Longitude", "Latitude"), crs = 4326)
# Create the reference 'sf' object
ref_point_sf <- st_point(c(5.04127, 52.92343)) %>%
st_coordinates() %>%
as.data.frame() %>%
st_as_sf(coords = c("X", "Y"), crs = 4326)
# Compute the distance between the reference point and points from 'df_sf'
results <- st_distance(ref_point_sf, df_sf) %>%
set_units("km")
- Output
results
#> Units: [km]
#> [,1] [,2] [,3] [,4] [,5] [,6]
#> [1,] 0 18.85446 0 0 0 0
Created on 2021-12-01 by the reprex package (v2.0.1)