【发布时间】:2017-08-19 15:57:38
【问题描述】:
我想知道是否有一种方法可以使用 apply 函数来执行以下矩阵填充?我读过 apply 比 for 循环更有效。出于某种原因,我在 apply 函数系列中挣扎。
我正在寻找填充矩阵。我使用数据框中的数据作为数据填充的条件。
以下是数据逻辑示例;它被简化了,但涵盖了基于规则的人口的基本要素。
id_1 <- c(1, 1, 1, 1, 1, 1)
id_2 <- c(1, 1, 2, 2, 3, 3)
id_3 <- c(1, 2, 2, 3, 3, 4)
amt <- c(10, 15, 20, 25, 30, 35)
sample_data <- data.frame(id_1, id_2, id_3, amt)
n <- length(sample_data)
cor <- matrix(ncol = n, nrow = n)
i <- 1
j <- 1
for (i in 1:n) {
for (j in 1:n) {
if (i == j) {
cor[i,j] = 1
} else if (sample_data[2][i,] == sample_data[2][j,] & sample_data[3][i,] != sample_data[3][j,]) {
cor[i,j] = 0
} else if (sample_data[2][i,] != sample_data[2][j,] & sample_data[3][i,] == sample_data[3][j,]) {
cor[i,j] = 0.5
} else {
cor[i,j] = 0.25
}
}
}
cor
[,1] [,2] [,3] [,4]
[1,] 1.00 0.00 0.25 0.25
[2,] 0.00 1.00 0.50 0.25
[3,] 0.25 0.50 1.00 0.00
[4,] 0.25 0.25 0.00 1.00
【问题讨论】:
标签: r