# make some example data
d <- data.frame(A = sample(1:10), B = sample(1:10), C = sample(1:10), D = sample(1:10))
# define what kind of rolling correlation we want to do
my_rollcor <- function(x) {
zoo::rollapply(
x, width = 3, by.column = FALSE, fill = NA,
FUN = \(y) cor(y[,1], y[,2])
)
}
# apply the rolling correlation to the combination of columns
out <- combn(d, 2, FUN = my_rollcor)
out <- as.data.frame(out)
# finally, make the correct names for those columns
names(out) <- combn(names(d), 2, \(x) paste0(x[[1]], x[[2]]))
# print the output
out
AB AC AD BC BD CD
1 NA NA NA NA NA NA
2 -0.85148509 0.93676591 0.2726855 -0.61413236 0.2723189 0.59213691
3 0.19966750 0.89340515 -0.3662897 0.61858957 0.8386279 0.09078413
4 0.93325653 0.84855529 0.3394221 0.98198051 0.6546537 0.78571429
5 0.18898224 0.94491118 0.1428571 0.50000000 -0.9449112 -0.18898224
6 -0.59030128 0.98974332 -0.6185896 -0.69955860 -0.2690610 -0.50000000
7 -0.09078413 0.92857143 -0.7857143 -0.45392065 -0.5447048 -0.50000000
8 -0.97986371 0.14803423 0.2448990 0.05241424 -0.4335550 -0.92261291
9 -0.38572714 -0.09078413 0.8660254 0.95382097 0.1272570 0.41931393
10 NA NA NA NA NA NA