gpt4 book ai didi

r - 定位停止/对角矩阵模式

转载 作者:行者123 更新时间:2023-12-04 02:45:12 25 4
gpt4 key购买 nike

我有一个二进制编码矩阵 (0/1) 矩阵,如下所示:

   X1 X2 X3 X4
1 1 0 0 1
2 0 0 0 0
3 0 0 0 0
4 1 1 1 0
5 1 1 0 0
6 0 0 1 0
7 1 0 1 0
8 0 0 1 0
9 0 0 1 0
10 0 0 0 0
11 1 1 0 0
12 0 0 0 1
13 0 0 0 1
14 0 0 0 1
15 0 0 0 0
16 0 1 1 0
17 1 1 0 0
18 1 0 1 0
19 1 0 1 0
20 1 1 1 1

我正在寻找一种可以通过视觉确定和描述但无法通过编程搜索来找到该模式的模式。这是模式:

我想找到停止并在下一行被不同列拾取的数字 1 的结束位置(如果列恰好并排,则对角线切换)。如果另一列会保持这一连串的 1,则对角线开关不算在内。

所以在上面的矩阵中,对角线切换发生在 x[5, 2] 到 x[6, 3] 并再次发生在 x[11, 1 (or 2)] 到 x[12, 4]

x <- structure(list(X1 = c(1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 
0, 0, 0, 1, 1, 1, 1), X2 = c(0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 1, 1, 0, 0, 1), X3 = c(0, 0, 0, 1, 0, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1), X4 = c(1L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 1L)), .Names = c("X1",
"X2", "X3", "X4"), row.names = c(NA, -20L), class = "data.frame")

这是一个很难描述的问题,但我想我已经用这个例子来说明它了。所需的输出将是 c(5, 11),因为这些是 1 具有此模式时的行。

我怀疑 rlecumsum 可能在这里有用。

编辑 为问题添加信息。我在不同的矩阵上尝试了 Ricardo 的初始解决方案:

   X1 X2 X3 X4 X5
1 0 0 1 0 0
2 1 1 0 0 1
3 0 0 0 0 0
4 0 0 1 0 0
5 0 1 1 0 0
6 1 0 1 1 0
7 1 1 0 0 0
8 0 0 1 1 1
9 0 0 1 0 0
10 1 1 0 1 0

rowdiffs <- apply(D, 2, diff)

N <- rowSums(rowdiffs==-1)
P <- rowSums(rowdiffs==1)

which(N - P > 0 & P > 0)

它给出:

## 7 
## 6

我希望 c(1, 7, 9) 可以在此处跟踪的行中看到。在每个红点,我别无选择,只能走对角线(这些是蓝色路径)。如果我到达全 0 的一行(黄色框),我将跳过该行并从下一行的路径(路径为橙色)重新开始(并且没有记录对角线模式)

enter image description here

D <- structure(list(X1 = c(0L, 1L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 1L), 
X2 = c(0L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 1L), X3 = c(1L,
0L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 0L), X4 = c(0L, 0L, 0L, 0L,
0L, 1L, 0L, 1L, 0L, 1L), X5 = c(0L, 1L, 0L, 0L, 0L, 0L, 0L,
1L, 0L, 0L)), .Names = c("X1", "X2", "X3", "X4", "X5"), row.names = c(NA,
10L), class = "data.frame")

最佳答案

尝试以下操作:

rowdiffs <- rbind(apply(D, 2, diff), NA)

N <- rowSums(rowdiffs==-1)
P <- rowSums(rowdiffs==1)

candidates <- which(N & P)
falseCandidates <- which(rowSums(rowdiffs==0 & D==1) >= 1)

setdiff(candidates, falseCandidates)
# [1] 1 7 9

说明:

将每一行与其下方的行进行比较 (rowdiffs)。
候选行将具有以下属性:

* contain both a `-1` and `+1` in the diffs 
(indicating the diagonal move)
* NOT contain a `0` in the diffs where there is a `1` in the original data
(indicating potential lateral move (or standard straight down))

关于r - 定位停止/对角矩阵模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18950973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com