I'm trying to calculate the center of each group, by running the calc_center
function with dplyr
's group_by_
and summarise
functions. However, I received an error saying that the column must be 1 column not two. What can I do to bypass it? This is my code.
library(dplyr)
library(car)
calc_center <- function(x,y){
MASS::cov.trob(cbind(x, y)$center
}
results <- data %>%
group_by(group) %>%
summarise(center=calc_center(Latitude, Longitude))
This is my error
Error in summarise_impl(.data, dots) :
Column center
must be length 1 (a summary value), not 2
In the future, it'd be nice if you included at least a brief example of your data for troubleshooting/reproducibility purposes.
The issue is likely because you'd like to apply the function to each row for the Latitude
and Longitude
columns.
In this case, using dplyr::rowwise()
should solve the issue:
E.g.;
results <- data %>%
group_by(group) %>%
rowwise() %>%
summarise(center=calc_center(Latitude, Longitude)) %>%
ungroup()
You could also probably get away with using mutate
instead of summarise
.
Hope that was helpful!