Suppose we perform a series of left_join() of data frames as shown below (please don't worry about appropriateness of left_join(), this is a simple example drawn from larger code which does require left_join()):
library(dplyr)
mydat <- data.frame(period = c(1, 2, 3, 4, 5, 6, 7, 8), plusA = c(10,20,12,13,17,19,20,16))
minus_B <- data.frame(period = c(1, 2, 3, 4, 5, 6, 7, 8), minusB = c(8,18,10,11,18,9,12,4))
equals_D <- data.frame(period = c(1, 2, 3, 4, 5, 6, 7, 8), equalsD = c(18,28,20,21,28,19,22,14))
mydat %>%
left_join(minus_B) %>%
left_join(equals_D)
period plusA minusB equalsD
1 1 10 8 18
2 2 20 18 28
3 3 12 10 20
4 4 13 11 21
5 5 17 18 28
6 6 19 9 19
7 7 20 12 22
8 8 16 4 14
I'm trying to add a balancing column, called "adjC", between the "minusB" and "equalsD" columns, that would leave a data frame output of:
period plusA minusB adjC equalsD [Explain column adjC]
1 1 10 8 16 18 18 - (10 - 8) = 16
2 2 20 18 26 28 28 - (20 - 18) = 26
3 3 12 10 18 20 etc.
4 4 13 11 19 21
5 5 17 18 27 28
6 6 19 9 9 19
7 7 20 12 16 22
8 8 16 4 2 14
I've been fooling around with mydat %>% mutate(adjust_C = equalsD - (plusA - minusB)), or inserting it into the middle of the above left_join() series, and it doesn't work.
Any ideas how to do this? I'm trying to stick with dplyr too.