I want to rescale all variables (but year
and gender
) in a df
by one specific year
, grouped by gender
:
Use position in mutate_at
library(dplyr)
df %>%
group_by(gender) %>%
mutate_at(-c(1, 2), ~ifelse(year == 3, 0, . - .[year == 3]))
# gender year var_a var_b
#
# 1 m 1 -2 -2
# 2 m 2 -1 -1
# 3 m 3 0 0
# 4 m 4 1 1
# 5 m 5 2 2
# 6 f 1 -2 -2
# 7 f 2 -1 -1
# 8 f 3 0 0
# 9 f 4 1 1
#10 f 5 2 2
In case, if you do not know the position of columns beforehand you can first find it
cols <- which(names(df) %in% c("gender", "year"))
df %>%
group_by(gender) %>%
mutate_at(-cols, ~ifelse(year == 3, 0, . - .[year == 3]))
Or select columns which starts_with
df %>%
group_by(gender) %>%
mutate_at(vars(starts_with("var")), ~ifelse(year == 3, 0, . - .[year == 3]))