我非常喜欢这个问题!这是一个解决方案,不一定很快,但它可以完成工作。
首先让我们重新创建您的数据:
a <- matrix(scan(textConnection("
0 0 0 0 1 0 0 1 1 0
1 0 0 0 1 0 0 0 0 0
0 1 1 0 1 1 0 0 1 1
0 0 1 1 0 1 0 1 0 0
0 0 0 1 0 1 0 0 0 1
1 0 0 0 0 1 0 1 0 0
0 1 1 1 1 1 1 0 1 0
1 0 1 0 1 0 0 0 1 1
1 1 1 0 0 0 0 0 0 0
1 1 1 1 1 0 1 0 1 0
")), 10, 10, byrow = TRUE)
在这里,让我们将行和列拆分为四个面向向量的列表:
rev.list <- function(l) lapply(l, rev)
v1 <- split(a, row(a)) # rows left to right
v2 <- rev.list(v1) # rows right to left
v3 <- split(a, col(a)) # cols up to down
v4 <- rev.list(v3) # cols down to up
在这里,我们创建并应用一个函数(灵感来自https://stackoverflow.com/a/17929557/1201032)来计算单向距离:
dir.dist <- function(v) {
out <- seq_along(v) - cummax(seq_along(v) * v)
out[seq_len(match(1, v) - 1)] <- NA
out
}
dist1.list <- lapply(v1, dir.dist) # dist to closest on left
dist2.list <- lapply(v2, dir.dist) # dist to closest on right
dist3.list <- lapply(v3, dir.dist) # dist to closest up
dist4.list <- lapply(v4, dir.dist) # dist to closest dn
现在让我们将所有内容放回四个矩阵中:
nr <- nrow(a)
nc <- ncol(a)
list.to.mat <- function(l, revert = FALSE, byrow = FALSE,
nrow = nr, ncol = nc) {
x <- unlist(if (revert) rev.list(l) else l)
matrix(x, nrow, ncol, byrow)
}
m1 <- list.to.mat(dist1.list, revert = FALSE, byrow = TRUE)
m2 <- list.to.mat(dist2.list, revert = TRUE, byrow = TRUE)
m3 <- list.to.mat(dist3.list, revert = FALSE, byrow = FALSE)
m4 <- list.to.mat(dist4.list, revert = TRUE, byrow = FALSE)
最后,让我们使用受https://stackoverflow.com/a/13123779/1201032pmean
启发的函数计算均值:
pmean <- function(..., na.rm = FALSE) {
dat <- do.call(cbind, list(...))
res <- rowMeans(dat, na.rm = na.rm)
idx_na <- !rowSums(!is.na(dat))
res[idx_na] <- NA
res
}
final <- matrix(pmean(as.vector(m1),
as.vector(m2),
as.vector(m3),
as.vector(m4), na.rm = TRUE), nr, nc)
final
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 2.50 2.50 2.00 2.00 0.00 1.67 3.00 0.0 0.00 1.50
# [2,] 0.00 1.67 1.67 2.00 0.00 1.00 3.50 2.0 2.00 3.00
# [3,] 1.67 0.00 0.00 1.00 0.00 0.00 2.33 1.5 0.00 0.00
# [4,] 2.00 1.67 0.00 0.00 1.50 0.00 1.67 0.0 1.67 1.33
# [5,] 2.33 2.00 1.33 0.00 1.50 0.00 2.00 1.5 2.00 0.00
# [6,] 0.00 2.25 2.00 1.75 *2.25* 0.00 1.00 0.0 1.67 1.67
# [7,] 1.00 0.00 0.00 0.00 0.00 0.00 0.00 1.0 0.00 1.33
# [8,] 0.00 1.00 0.00 1.25 0.00 1.67 1.75 2.0 0.00 0.00
# [9,] 0.00 0.00 0.00 1.33 1.33 2.50 2.33 4.0 2.67 4.00
# [10,] 0.00 0.00 0.00 0.00 0.00 1.67 0.00 2.0 0.00 1.50