I have a dataset that looks like this:
site lat long
bras2 41.21 -115.11
tex4 45.3 -112.31
bras2 41.15 -115.15
bras2 41.12 -115.19
For samples with the same site name, I want to calculate their centre point and then add it as a column to the dataset. Some site names are duplicated twice, other three times, other four times.
Like this:
site lat long centre_lat centre_long
bras2 41.21 -115.11 value here value here
tex4 45.3 -112.31 45.3 -112.31
bras2 41.15 -115.15 value here value here
bras2 41.12 -115.19 value here value here
How can I do this?
If you're using spatial data, you should look into using the
sfpackage. It handles geometries and functions for operating on them well.Code below shows using both
sf::st_centroidandgeosphere::centroid. I prefersf's way of doing things.Looks like thery're close enough to the same point. I don't think
geosphere::centroidcan give a centroid for a single point, but may be wrong.sf::st_centroidhas no problem with 1,2, or more points. Created on 2020-12-20 by the reprex package (v0.3.0)