Currently, I am working on the following problem:
I am trying to split my dataset in groups and create a new variable that captures the group mean of all opposite cases that do not belong to this group - for a specific time frame.
Here is a replica of my code using the mpg dataset.
cars <- mpg
cars$other_cty_yearly_mean <- 0
for(i in cars$cyl){
cars <- cars %>%
group_by(year) %>%
mutate(other_cty_yearly_mean = if_else(
cyl == i,
mean(cty[cyl != i]),
other_cty_yearly_mean
)) %>%
ungroup() %>%
as.data.frame()
}
Is there any better way that does not make a for loop necessary?
Thanks and best!