I'm trying to create a for loop to return the centroid positions from a data frame. Basically I've got 451 unique tracking ID's in this dataframe, each with about 125 observations of longitude and latitude. I want to create a dataframe that gives me the centroid lon and lat for all 451 ID's. The approach I'm using is creating an empty data frame then running a for loop to store all the results in that dataframe.
Here's what I've written:
forage.central <- as.tibble(data.frame(matrix(ncol = 2, nrow = 451)))
for(i in unique(tow_dat$track_ID)){
current_data <- tow_dat %>% filter(track_ID == i) %>%
dplyr::select(lon,lat)
print(centroid(current_data))
forage.central[i] <- centroid(current_data)
}
And I'm getting this output:
lon lat
[1,] 151.9351 -27.58116
Error in `[<-`:
! Can't recycle input of size 2 to size 1.
Run `rlang::last_trace()` to see where the error occurred.
Any suggestions?
Despite specifically asking for for-loops and
geospeher, I'd suggest usingsfinstead, current de facto R library for spatial (vector) data. Withsfyour problem automagically turns into a simplegroup_by()/summarise()task:As a side note, depending on collected track points you may want to work with some other metrics like centroids of (convex) hulls. My selected dataset isn't the best example for this, but the difference between methods is still clearly visible:
Created on 2023-07-28 with reprex v2.0.2
You may also want to skim through following CRAN task views:
https://cran.r-project.org/web/views/Tracking.html
https://cran.r-project.org/web/views/SpatioTemporal.html
There are quite a few libraries targeting trajectory analysis and more often than not someone has already solved and tested a solution for that new-to-you problem.