I'm trying to do something that intuitively feels straightforward but I can't figure it out. I'm hoping to calculate delta's for a number of columns: I have columns A1, B1, C1
and A2, B2, C2
and would like to create columns A_delta, B_delta, C_delta
by subtracting A2 - A1
etc.
Here's what I thought I could do with dplyr
(using mtcars
as example):
# Create test data with changed columns
d.test <- mtcars %>%
rownames_to_column() %>%
mutate(mpg2 = mpg - 4,
cyl2 = cyl - 1)
# Calculate deltas & add as new columns
d.test %>% mutate(!!c("mpg_delta", "cyl_delta") := c(mpg2, cyl2) - c(mpg, cyl))
Clearly it doesn't work like this, but I cannot for the life of me figure out the right syntax. I've been reading up on using purrr
but that seems applicable when trying to do different actions per row (like here dplyr mutate using variable columns), not when trying to create multiple new columns...
Any pointers would be great!