I'm sure I'm missing something about how grouping works. When I use my own function within a summarize statement (after grouping) I get the same result for each group, which is wrong. Also I don't get any errors or warnings, it's just silently giving me the wrong answer.
My goal is to get this custom function to play nice with group_by.
Here is the code:
library(dplyr)
#data
transect <- data.frame(acronym = c("ABEESC", "ABIBAL", "AMMBRE", "ANTELE", "ABEESC", "ABIBAL", "AMMBRE"),
quad_id = c(1, 1, 1, 1, 2, 2, 2))
#scores
c_scores <- data.frame(acronym = c("ABEESC", "ABIBAL", "AMMBRE", "ANTELE"),
c = c(5, 6, 6, 10))
#custom fun
my_fun <- function(data, scores){
join <- left_join(data, scores, by = "acronym")
mean <- mean(join$c)
return(mean)
}
#this works
my_fun(transect, c_scores)
#this also works
transect %>% my_fun(., c_scores)
#this doesn't...
transect %>%
group_by(quad_id) %>%
summarise(mean_c = my_fun(., scores = c_scores))
this is my result:
quad_id | mean_c |
---|---|
1 | 6.29 |
2 | 6.29 |
this is what I want:
quad_id | mean_c |
---|---|
1 | 6.75 |
2 | 5.66 |