我有以下代码来交叉制表 R 中 2D 网格中内部单元格的相邻邻居(水平)的数量。
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)),])
这产生:
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
我得到 tmp 作为维度的数组(表):
dim(tmp)
[1] 2 3 3
一般来说,上述工作,除了(在某种程度上)以下微不足道的情况。
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)),])
我得到:
tmp
, , = 2
2
0 32
答案没有错,但对我来说不方便,因为我不再得到维度为 c(2,3,3) 的 3D 数组,因为交叉表中缺少的组合已被消除。tmp 现在是一个数组
dim(tmp)
[1] 1 1 1
如何将上述转换为具有维度表/数组,c(2,3,3)
而其他组合为零?