I have the following code to cross-tabulate the number of adjacent neighbors (horizontal) for an interior cell in a 2D grid in R.
set.seed(1234)
x <- matrix(sample(0:1, size = 10*6, replace = T), nr = 10)
likes.x <- 1*(x[-nrow(x),] == x[-1,])
nonedge.likes.x <- (likes.x[-nrow(likes.x),]+likes.x[-1,])
edge.likes.x <- rbind(likes.x[1,], likes.x[nrow(likes.x),])
likes.y <- 1*(x[,-ncol(x)] == x[,-1])
nonedge.likes.y <- (likes.y[,-ncol(likes.y)]+likes.y[,-1])
edge.likes.y <- cbind(likes.y[,1], likes.y[,ncol(likes.y)])
tmp <- table(x[-c(1,nrow(x)),-c(1,ncol(x))], nonedge.likes.x[,-c(1,ncol(likes.x))], nonedge.likes.y[-c(1, nrow(likes.y)),])
This yields:
tmp
, , = 0
0 1 2
0 2 4 1
1 0 2 1
, , = 1
0 1 2
0 2 0 1
1 2 6 3
, , = 2
0 1 2
0 1 0 1
1 0 2 4
I get tmp as an array (table) of dimension:
dim(tmp)
[1] 2 3 3
The above works, in general, except (in a way) for the following trivial case.
x <- matrix(0, nr = 10, nc = 6)
likes.x <- 1*(x[-nrow(x),] == x[-1,])
nonedge.likes.x <- (likes.x[-nrow(likes.x),]+likes.x[-1,])
edge.likes.x <- rbind(likes.x[1,], likes.x[nrow(likes.x),])
likes.y <- 1*(x[,-ncol(x)] == x[,-1])
nonedge.likes.y <- (likes.y[,-ncol(likes.y)]+likes.y[,-1])
edge.likes.y <- cbind(likes.y[,1], likes.y[,ncol(likes.y)])
tmp <- table(x[-c(1,nrow(x)),-c(1,ncol(x))], nonedge.likes.x[,-c(1,ncol(likes.x))], nonedge.likes.y[-c(1, nrow(likes.y)),])
I get:
tmp
, , = 2
2
0 32
The answer is not wrong, but inconvenient for me, in the sense that I no longer get a 3D array of dimension c(2,3,3) because missing combinations in the cross-tabulations have been eliminated. tmp is now an array of
dim(tmp)
[1] 1 1 1
How do I convert the above to have a table/array of dimension c(2,3,3) with the other combinations being zeros?
The problem you pose is ill-defined.
After your first code block, look at:
So you get a 2x3x3 result. The dimensions of the first result is simply the number of unique elements of arg1 by number of unique elements in arg2 by number of unique in arg3.
There's no way the code in the second instance can "know" that your prior problem had such ranges of values. You need to specify what features of the problem you expect the result to reflect.
I suppose you could ask for a 3x3x3 array with 2 in the lower right back corner, but that would be implying that you thought both of the answers for
tmpwere wrong to begin with.