1) sapply 对指定的函数执行双重sapply。我们可以选择在此使用 as.dist 并在稍后显示的其他替代方案上类似地使用,但不会对每个都重复。
nc <- ncol(m)
res <- sapply(1:nc, function(i) sapply(1:nc, function(j) sum(m[, i] != m[, j])))
res
## [,1] [,2] [,3]
## [1,] 0 1 3
## [2,] 1 0 2
## [3,] 3 2 0
或
as.dist(res)
## 1 2
## 2 1
## 3 3 2
2) 列表理解 使用 eList 包,我们可以像这样生成它:
library(eList)
nc <- ncol(m)
Mat(for(i in 1:nc) for(j in 1:nc) sum(m[, i] != m[, j]))
## [,1] [,2] [,3]
## [1,] 0 1 3
## [2,] 1 0 2
## [3,] 3 2 0
3) 外层 我们可以像这样使用outer:
f <- function(i, j) sum(m[, i] != m[, j])
outer(1:nc, 1:nc, Vectorize(f))
## [,1] [,2] [,3]
## [1,] 0 1 3
## [2,] 1 0 2
## [3,] 3 2 0
注意
m <- structure(c("A", "A", "B", "A", "C", "B", "B", "C", "D"), .Dim = c(3L,
3L), .Dimnames = list(c("Att1", "Att2", "Att3"), c("Ind1", "Ind2",
"Ind3")))