Reputation: 634
I'm looking for an efficient solution (preferably C++) to replace this code:
m <- cbind(x1=1:10,x2=1:10,x3=1:10)
width=3
rol_m <- zoo::rollapplyr(m, width=width, c, fill=NA)
colnames(rol_m) <- sapply(colnames(m), rep, width) |> c() |> make.unique()
x1 x1.1 x1.2 x2 x2.1 x2.2 x3 x3.1 x3.2
[1,] NA NA NA NA NA NA NA NA NA
[2,] NA NA NA NA NA NA NA NA NA
[3,] 1 2 3 1 2 3 1 2 3
[4,] 2 3 4 2 3 4 2 3 4
[5,] 3 4 5 3 4 5 3 4 5
[6,] 4 5 6 4 5 6 4 5 6
[7,] 5 6 7 5 6 7 5 6 7
[8,] 6 7 8 6 7 8 6 7 8
[9,] 7 8 9 7 8 9 7 8 9
[10,] 8 9 10 8 9 10 8 9 10
This code simply builds a matrix with a sliding window for each column m
.
Also important to me is the fill=NA
argument.
And it is advisable to save the column names.
Is there a package that contains an effective implementation of something like this?
Upvotes: 0
Views: 50
Reputation: 634
effective rollapply
alternative is written in C++
m <- cbind(x1=1:10,x2=1:10,x3=1:10)
width=3
library(runner)
runner(m, k=width, f=c, na_pad = T) |> do.call(what="rbind")
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] NA NA NA NA NA NA NA NA NA
[2,] NA NA NA NA NA NA NA NA NA
[3,] 1 2 3 1 2 3 1 2 3
[4,] 2 3 4 2 3 4 2 3 4
[5,] 3 4 5 3 4 5 3 4 5
[6,] 4 5 6 4 5 6 4 5 6
[7,] 5 6 7 5 6 7 5 6 7
[8,] 6 7 8 6 7 8 6 7 8
[9,] 7 8 9 7 8 9 7 8 9
[10,] 8 9 10 8 9 10 8 9 10
Upvotes: 0