对于那些熟悉分析层次结构过程的人来说,这应该更加直观......
使用以下代码创建data.frame criteria
:
c <- 5
cri_names <- c("Applicability", "Deployment", "Scalability", "Ease-of-Use", "TCO")
c1 <- data.frame(c = rep(0, c))
criteria <- data.frame(do.call("cbind", rep(c1, c)))
colnames(criteria) <- cri_names
rownames(criteria) <- cri_names
cvs <- data.frame(c1 = c(1, 5, 3, 1, 3),
c2 = c(1, 1, 1/3, 1/5, 1/5),
c3 = c(1, 1, 1, 1/3, 3),
c4 = c(1, 1, 1, 1, 5),
c5 = c(1, 1, 1, 1, 1))
for(v in c(1:ncol(cvs))) {
criteria[v, ] <- cvs[, v]
}
print(criteria)
# Applicability Deployment Scalability Ease-of-Use TCO
#Applicability 1 5 3.0000000 1.0000000 3.0
#Deployment 1 1 0.3333333 0.2000000 0.2
#Scalability 1 1 1.0000000 0.3333333 3.0
#Ease-of-Use 1 1 1.0000000 1.0000000 5.0
#TCO 1 1 1.0000000 1.0000000 1.0
我现在要做的是将1
左侧的每个criteria[x, x]
替换为其相反值的倒数。例如:
criteria["Deployment", "Applicability"] <- 1/criteria["Applicability", "Deployment"]
最终结果应如下所示:
# Applicability Deployment Scalability Ease-of-Use TCO
#Applicability 1.0000000 5 3.0000000 1.0000000 3.0
#Deployment 0.2000000 1 0.3333333 0.2000000 0.2
#Scalability 0.3333333 3 1.0000000 0.3333333 3.0
#Ease-of-Use 1.0000000 5 3.0000000 1.0000000 5.0
#TCO 0.3333333 5 0.3333333 0.2000000 1.0
我非常有信心可以通过嵌套for循环实现这一点,但我无法理解它,而且我的工作时间已经不多了。
答案 0 :(得分:2)
我认为这是你正在寻找的东西:
l <- lower.tri(criteria)
criteria[l] <- 1/t(criteria)[l]
print(criteria)
## Applicability Deployment Scalability Ease-of-Use TCO
## Applicability 1.0000000 5 3.0000000 1.0000000 3.0
## Deployment 0.2000000 1 0.3333333 0.2000000 0.2
## Scalability 0.3333333 3 1.0000000 0.3333333 3.0
## Ease-of-Use 1.0000000 5 3.0000000 1.0000000 5.0
## TCO 0.3333333 5 0.3333333 0.2000000 1.0
仅供参考,这不会起作用:
criteria[lower.tri(criteria)] <- 1/criteria[upper.tri(criteria)]
您希望下三角形的列填充上三角形的行的倒数。但是,R按列读取矩阵,因此criteria[upper.tri(criteria)]
将返回以下内容:
[1] 5.0000000 3.0000000 0.3333333 1.0000000 0.2000000 0.3333333 3.0000000 0.2000000 3.0000000 5.0000000
这可以通过转置并获得下三角来解决,这相当于取上三角形的行。