Not that it's any better, but still wanted to share it because I was interested in the problem and ws trying for sometime to incorporate something like identity for non-numeric columns and then use Reduce, but failed.
Here's what I did:
set.seed(seed = 1)
N <- 6
df_1 <- data.frame(Dates = seq(from = as.Date(x = "2019-01-01",
format = "%Y-%m-%d"),
length.out = N,
by = 'day'),
Product = rep(x = "A",
each = N),
A1 = runif(n = N),
A2 = runif(n = N),
B1 = runif(n = N),
B2 = runif(n = N),
B3 = runif(n = N),
C1 = runif(n = N),
C2 = runif(n = N))
df_2 <- data.frame(Dates = seq(from = as.Date(x = "2019-01-01",
format = "%Y-%m-%d"),
length.out = N,
by = 'day'),
Product = rep(x = "B",
each = N),
A1 = runif(n = N),
A2 = runif(n = N),
B1 = runif(n = N),
B2 = runif(n = N),
B3 = runif(n = N),
C1 = runif(n = N),
C2 = runif(n = N))
numeric_operation <- function(numeric_column_name)
{
if (startsWith(x = numeric_column_name,
prefix = "A"))
{
return(`/`)
} else if (startsWith(x = numeric_column_name,
prefix = "B"))
{
return(`-`)
} else if (startsWith(x = numeric_column_name,
prefix = "C"))
{
return(`+`)
} else
{
stop("Unknown operation - STOP!!!")
}
}
operation <- function(df_1_column_name)
{
df_1_column <- df_1[[df_1_column_name]]
df_2_column <- df_2[[df_1_column_name]]
if (is.null(x = df_2_column))
stop("Column name mismatch - STOP!!!")
if (!is.numeric(x = df_2_column))
{
if (!identical(x = df_1_column,
y = df_2_column))
{
warning("Non-numeric non-identical column - SKIPPED!!!")
return(NULL)
}
return(df_2_column)
}
return(numeric_operation(df_1_column_name)(df_1_column, df_2_column))
}
as.data.frame(x = Filter(f = Negate(f = is.null),
x = sapply(X = names(x = df_1),
FUN = operation,
simplify = FALSE,
USE.NAMES = TRUE)))
#> Warning in FUN(X[[i]], ...): Non-numeric non-identical column - SKIPPED!!!
#> Dates A1 A2 B1 B2 B3
#> 1 2019-01-01 0.3391206 1.2899871 0.61634380 -0.532840745 -0.21132458
#> 2 2019-01-02 0.6728743 0.9539017 0.28463756 0.483841849 -0.38019658
#> 3 2019-01-03 1.0814276 1.3171863 0.45356971 0.475639505 -0.07085658
#> 4 2019-01-04 1.1505677 0.0717436 -0.02093502 -0.120252153 -0.49293337
#> 5 2019-01-05 8.6443008 0.4701573 0.05561343 0.000803299 0.53061791
#> 6 2019-01-06 1.8825086 0.7212366 0.58507591 -0.132461685 -0.49909135
#> C1 C2
#> 1 0.8287636 1.5715606
#> 2 0.9333408 1.0685616
#> 3 0.9698926 1.1583704
#> 4 1.0784159 1.1237891
#> 5 1.6917128 1.2209407
#> 6 1.0584563 0.9724123