0

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

2 Answers2

3

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!

Jared Wilber
  • 6,038
  • 1
  • 32
  • 35
  • 1
    This was super helpful to me. It took me an embarrassingly long time to see that I was trying to pass the whole df to the function inside `summarize`, and not just 1 column. I decided to use `map_dfr` on unique values of one variable, sort of like this: `map_dfr(unique(my.df$mycol), function(x){newval<-my.df %>% filter(mycol==x) %>% myfun return(newval, x})` – Michael Roswell Feb 22 '19 at 17:53
0

The problem is in your function calc_center, the y in cov.trob is getting assigned to wt

In ?MASS::cov.trob

cov.trob(x, wt = rep(1, n), cor = FALSE, center = TRUE, nu = 5,
     maxit = 25, tol = 0.01)

You will see that x is of type matrix, this will hold your latitude and longitude

Kevin Arseneau
  • 6,186
  • 1
  • 21
  • 40