I have a data.frame
similar to this one:
library(tidyverse)
df <- data.frame(
var_1_a = 1:100,
var_1_b = 101:200,
var_two_a = 5:104,
var_two_b = 1:100
)
head(df)
var_1_a var_1_b var_two_a var_two_b
1 1 101 5 1
2 2 102 6 2
3 3 103 7 3
4 4 104 8 4
5 5 105 9 5
6 6 106 10 6
And I want to take the difference of the similarly-named variables. Since there's only two here, that's easy to do with something like:
df %>%
mutate(var_1_new = var_1_a - var_1_b,
var_two_new = var_two_a - var_two_b)
But in the real data I have about a hundred of these. What is the easier way of doing this rather than typing them all out?
PS - If it makes it easier, I have a list with all the variables (e.g. mylist <- list("var_1", "var_two")