Reputation: 2378
I would like to apply a rolling window pattern update on a matrix. Say I have a matrix of zeros and ones like so:
mat <- matrix(c(0,1,1,0,1,1,0,0,1,1,1,0,1,0,0,0),nrow=4)
0 1 1 1
1 1 1 0
1 0 1 0
0 0 0 0
I want to scan each row of the matrix 2 values at a time and create a matrix of labels based on this set of rules:
0 0 - then label as A
0 1 - then label as B
1 0 - then label as B
1 1 - then label as C
The desired output for the above matrix is:
(the NA
values appear because the first value does not have a value before it)
NA B C C
NA C C B
NA B B B
NA A A A
I am trying to implement this in R
. Is there a way to do this using one of the apply methods? Or is there a quick approach storing this data as a data.frame and processing using packages such as dplyr
or data.table
? Currently, I am processing it as a for
loop (which is, of course, very very slow).
Upvotes: 3
Views: 98
Reputation: 66819
The rolling operation here acts on pairwise combinations, so you can just define the function:
f <- function(x,y) LETTERS[1:3][x+y+1L]
and then apply it to the appropriate pairs:
nc <- ncol(m)
res <- matrix(,length(m)/nc,nc)
res[,-1] <- f(m[,-nc], m[,-1])
# [,1] [,2] [,3] [,4]
# [1,] NA "B" "C" "C"
# [2,] NA "C" "C" "B"
# [3,] NA "B" "B" "B"
# [4,] NA "A" "A" "A"
Upvotes: 6