Вы можете использовать функцию left_join
на dplyr
, аналоге LEFT JOIN
SQL.В вашем случае в упрощенном виде это будет ISL %>% left_join(SLS, by = "Article")
.Пожалуйста, смотрите полный код ниже:
# data.frame simulation
strs3 <- c("Brand", "Cust", "Article", "201808change", "201809change", "201903change", "201904change", "201905change",
"201906change", "201907change", "201811change", "201812change", "201901change")
n <- 1000
total <- cbind(
as.data.frame(matrix(sample(LETTERS, 3 * n, replace = TRUE), ncol = 3)),
matrix(rnorm(n * 10), ncol = 10)
)
names(total) <- c("Brand", "Cust", "Article", "201808change", "201809change", "201903change", "201904change", "201905change",
"201906change", "201907change", "201811change", "201812change", "201901change")
spl <- ceiling(n * 57 / 58)
ils <- total[1:spl, ]
u <- unique(ils$Article)
ul <- length(u)
slt <- total[(spl + 1): (spl + ul), ]
slt$Article <- u
# left join
z <- ils %>% left_join(slt, by = "Article") %>%
mutate(`201811change` = `201811change.x` - `201811change.y`) %>%
mutate(`201812change` = `201812change.x` - `201812change.y`) %>%
mutate(`201901change` = `201901change.x` - `201901change.y`) %>%
select(-ends_with("y")) %>% select(-one_of("201811change.x", "201812change.x", "201901change.x"))
str(z)
Вывод (структура результирующего фрейма данных):
'data.frame': 983 obs. of 13 variables:
$ Brand.x : Factor w/ 26 levels "A","B","C","D",..: 16 23 19 20 19 26 7 21 22 9 ...
$ Cust.x : Factor w/ 26 levels "A","B","C","D",..: 21 15 25 3 24 2 1 26 3 23 ...
$ Article : Factor w/ 26 levels "A","B","C","D",..: 13 14 2 17 23 13 4 1 17 15 ...
$ 201808change.x: num -1.398 -0.357 -1.042 -0.653 -1.037 ...
$ 201809change.x: num 1.483 0.604 0.276 0.846 -1.245 ...
$ 201903change.x: num -0.733 -0.413 0.61 -1.037 1.048 ...
$ 201904change.x: num -0.794 -1.0688 0.577 0.3368 0.0472 ...
$ 201905change.x: num -0.427 -0.898 1.124 -0.435 -0.304 ...
$ 201906change.x: num 2.094 0.177 -0.892 -1.655 -1.091 ...
$ 201907change.x: num 0.228 0.546 0.141 -1.166 -0.687 ...
$ 201811change : num 1.5082 0.0148 -0.5335 -0.763 -1.7196 ...
$ 201812change : num 1.415 -2.128 -0.576 1.205 -0.631 ...
$ 201901change : num -0.883 -0.892 -2.032 -2.172 0.483 ...