It seems like the code breaks down when there is a date variable, as shown in reprex below. I'm now guessing that unmatched variables in x has to be set aside then stitched together after with either left or full_join or cbind. Or is there a more elegant solution?
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
x = data.frame(
var1 = 1:3,
var2 = 2:4,
var3 = 3:5,
var4 = 4:6,
var5 = 5:7,
yearr = sample(2015:2021, 3, replace = TRUE),
monthh = sample(1:12, 3, replace = TRUE),
dayy = sample(1:28, 3, replace = TRUE)) |>
mutate(datee = ymd(paste(yearr, monthh, dayy))) |>
select(-yearr, -monthh, -dayy)
y = data.frame(
var1 = 2,
var3 = 7,
var5 = 3
)
compute_desired_output = function(x, y){
uncommon_cols = setdiff(colnames(x), colnames(y))
y[uncommon_cols] = 1
y = y[colnames(x)]
as.matrix(x) %*% t(y)
}
compute_desired_output(x = x, y = y)
#> Error in as.matrix(x) %*% t(y): requires numeric/complex matrix/vector arguments
Created on 2021-08-09 by the reprex package (v2.0.0)