r - Getting the centroids of Lat and Longitude in a data frame -


i have dataframe (df) has 3 column likes so: (all numbers random)

id  lat    lon 1   25.32 -63.32 1   25.29 -64.21 1   24.12 -62.43 2   12.42  54.64 2   12.11  53.43 .   ....   .... 

basically wanted have centroid per id so:

id  lat    lon    cent_lat   cent_lon 1   25.32 -63.32  25.31      -63.25 1   25.29 -64.21  25.31      -63.25 1   24.12 -62.43  25.31      -63.25 2   12.42  54.64  12.20       53.60 2   12.11  53.43  12.20       53.60 

i tired following:

library(geosphere) library(rgeos) library(dplyr)  df1 <- by(df,df$id,centroid(df$lat, df$long)) 

but gave me error:

error in (function (classes, fdef, mtable): unable find inherited method function ‘centroid’ signature ‘"numeric"’

i tired

df1 <- by(df,df$id,centroid(as.numeric(df$lat), as.numeric(df$long))) 

but gave me error:

error in (function (classes, fdef, mtable) : unable find inherited method function ‘centroid’ signature ‘"function"’

here's data.table approach. @czeinerb mentioned, lon first argument of centroid function, , lat second. re-define centroid function below that, in data.table aggregation, receives matrix 2 columns (lat|lon), required input geosphere's centroid function.

# import packages library(geosphere) library(data.table) # using data.table approach  # sample data df = data.frame("id" = c(1, 1, 1, 2, 2, 2), "lat" = c(25.32, 25.29, 24.12, 12.42, 12.11, 12.22), "lon" = c(-63.32, -64.21, -62.43, 54.64, 53.43, 53.23))  df    id   lat    lon 1  1 25.32 -63.32 2  1 25.29 -64.21 3  1 24.12 -62.43 4  2 12.42  54.64 5  2 12.11  53.43 6  2 12.22  53.23  # convert data.table setdt(df)  # re-define centroid function - lon first argument , lat second # geosphere takes matrix 2 columns: lon|lat, use cbind coerce data form findcentroid <- function(lon, lat, ...){   centroid(cbind(lon, lat), ...) }  # find centroid lon , lat id, required df[, c("cent_lon", "cent_lat") := as.list(findcentroid(lon, lat)), = id] df     id   lat    lon  cent_lon cent_lat 1:  1 25.32 -63.32 -63.32000 24.91126 2:  1 25.29 -64.21 -63.32000 24.91126 3:  1 24.12 -62.43 -63.32000 24.91126 4:  2 12.42  54.64  53.76667 12.25003 5:  2 12.11  53.43  53.76667 12.25003 6:  2 12.22  53.23  53.76667 12.25003 

Comments