【发布时间】:2015-06-20 20:22:35
【问题描述】:
这个问题很难解释,但我相信你们中的一些人已经遇到过。
所以我有两个矩阵。 矩阵 1 (mat 1) 和 矩阵 2 (mat 2)
我想要做的是在第三个矩阵 (mat3) 中记录 mat2 的值,在检查矩阵 1 之后,但带有 LAG。让我解释。
在矩阵 1 中的值 1 之后,我想检查矩阵 2 是否也是 1 但在某个 LAG 的范围内,例如 1 或(列)之后的 2 集。
例如,第 4 行在第 6 列的矩阵 1 中具有 1。 因此,我想检查矩阵 2 中第 4 行的 1 是否直接在 2 或 3 列之后或之后。
你明白这个想法吗?
mat1 = structure(c(0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0,
0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0,
0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0,
1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1,
0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0,
0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1), .Dim = c(10L, 21L), .Dimnames = list(NULL, c("wit5.020",
"wit5.021", "wit5.022", "wit5.023", "wit5.024", "wit5.025", "wit5.026",
"wit5.027", "wit5.028", "wit5.029", "wit5.030", "wit5.031", "wit5.032",
"wit5.033", "wit5.034", "wit5.035", "wit5.036", "wit5.037", "wit5.038",
"wit5.039", "wit5.040")))
mat2 = structure(c(0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0,
0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0,
0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0,
0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0,
1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1,
0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0,
1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1,
0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0,
0, 1, 0, 1), .Dim = c(10L, 21L))
所以 mat3 - 我想存储检查结果的地方
mat3 = matrix(0, nrow = nrow(mat1), ncol = ncol(mat1))
所以这里是一个可能的循环的例子 为了检查 LAG - 这个 循环不起作用 但它可以让您了解解决方案。 我不确定在哪里引入滞后。我想也许在 i 中,但我不确定。
for(j in 1:ncol(mat1)){
for(i in 1:nrow(mat1)){
if( mat1[i,j] == 1 & mat2[i,j] == 1 | mat2[i+1,j] == 1 | mat2[i+2,j] == 1) # lag here
{mat[i,j] <- 1}
else
{mat[i,j] <- 0}
}
}
非常欢迎任何想法。
【问题讨论】:
-
mat1.wake和mat是什么? t 应分别为mat1和mat3。另外,如果根据您的描述,您想要落后于列 (j),为什么还要落后于行 (i)?如果您只遵循自己的解释,我相信您可以使这个循环工作。 -
@DavidArenburg 对不起 mat1.wake 是 mat1 !我的错
-
不管怎样,你可以尝试如下vectorise,但我不太喜欢这种方法
indx <- mat1 == 1L ; mat3[indx] <- (mat2[indx] == 1L) |(cbind(mat2[, -1L], FALSE)[indx] == 1L) |(cbind(mat2[, -(1L:2L)], FALSE, FALSE)[indx] == 1L) -
@DavidArenburg - 是的,我必须在 j 上滞后 - 你是对的。我意识到我真正想要的更复杂。我需要更清楚地弄清楚。谢谢。
-
@DavidArenburg - 所以我需要将 1 存储在
mat3,而不是mat[i,j],而只是存储在之前的每一列中。因此,当循环在矩阵 1 中找到 1 时(有滞后),然后将 1 放在矩阵 3 之前的每一列中。有什么线索吗?谢谢