5
I have the following code:
df <- data.frame(grp = rep(letters[1:3], each = 2),
index = rep(1:2, times = 3),
value = seq(10, 60, length.out = 6),
value2 = seq(20, 70, length.out = 6),
value3 = seq(30, 80, length.out = 6))
library(tidyverse)
tbl_df(df) #para melhor visualização
# grp index value value2 value3
# <fct> <int> <dbl> <dbl> <dbl>
# 1 a 1 10 20 30
# 2 a 2 20 30 40
# 3 b 1 30 40 50
# 4 b 2 40 50 60
# 5 c 1 50 60 70
# 6 c 2 60 70 80
# resultado esperado:
# grp index value value2 value3
# <fct> <int> <dbl> <dbl> <dbl>
# 1 a 1 10 20 30
# 2 a 2 20 30 40
# 3 b 1 -20 -20 -20
# 4 b 2 -20 -20 -20
# 5 c 1 50 60 70
# 6 c 2 60 70 80
# subtrair um grupo de outro
df$value[df$grp=="b"] = df$value[df$grp=="b"] - df$value[df$grp=="c"]
df$value2[df$grp=="b"] = df$value2[df$grp=="b"] - df$value2[df$grp=="c"]
df$value3[df$grp=="b"] = df$value3[df$grp=="b"] - df$value3[df$grp=="c"]
How to subtract all value# group 'c' of value# group 'b', at once, without the need to repeat
df$value[df$grp=="b"] = df$value[df$grp=="b"] - df$value[df$grp=="c"]
for each variable?