r - 如何从矩阵中仅获取一个连接

标签 r matrix dplyr

我有一个矩阵,如下所示

       ID_1 ID_2 ID_3 ID_4 ID_8 ID_5 ID_7 ID_100
ID_1      0    1    1    1  Inf    2    2    Inf
ID_2      1    0    2    1  Inf    1    2    Inf
ID_3      1    2    0    2  Inf    3    1    Inf
ID_4      1    1    2    0  Inf    2    1    Inf
ID_8    Inf  Inf  Inf  Inf    0  Inf  Inf      1
ID_5      2    1    3    2  Inf    0    3    Inf
ID_7      2    2    1    1  Inf    3    0    Inf
ID_100  Inf  Inf  Inf  Inf    1  Inf  Inf      0

我使用了 as.data.frame.tablefilter 因为我只想要那些具有 3 的值。输出看起来像

  nodeA nodeB score
1  ID_5  ID_3     3
2  ID_3  ID_5     3
3  ID_7  ID_5     3
4  ID_5  ID_7     3

我写的代码

mat_pi_lon <- as.data.frame.table(mat, responseName = "score") %>%
  filter(score ==3) %>%
  rename(nodeA = Var1, nodeB = Var2)

但是,我的实际预期输出如下所示。因为,ID_3 ID_5 3 和 ID_5 ID_3 3 是相同的(就概念而言)。因此,我只想要 ID_3 ID_5 3,而不是 ID_5 ID_3 3

  nodeA nodeB score
1  ID_3  ID_5     3
2  ID_5  ID_7     3

是否可以减少输出?

可重复的数据

structure(c(0, 1, 1, 1, Inf, 2, 2, Inf, 1, 0, 2, 1, Inf, 1, 2, 
Inf, 1, 2, 0, 2, Inf, 3, 1, Inf, 1, 1, 2, 0, Inf, 2, 1, Inf, 
Inf, Inf, Inf, Inf, 0, Inf, Inf, 1, 2, 1, 3, 2, Inf, 0, 3, Inf, 
2, 2, 1, 1, Inf, 3, 0, Inf, Inf, Inf, Inf, Inf, 1, Inf, Inf, 
0), .Dim = c(8L, 8L), .Dimnames = list(c("ID_1", "ID_2", "ID_3", 
"ID_4", "ID_8", "ID_5", "ID_7", "ID_100"), c("ID_1", "ID_2", 
"ID_3", "ID_4", "ID_8", "ID_5", "ID_7", "ID_100")))

最佳答案

您可以先将 upper.tri 替换为 NA,从而节省一些步骤。

library(dplyr)
mat %>%
  replace(., upper.tri(.), NA) %>%
  as.data.frame.table(responseName="score") %>%
  filter(score %in% 3)
#   Var1 Var2 score
# 1 ID_5 ID_3     3
# 2 ID_7 ID_5     3

使用基础 R:

mat[upper.tri(mat)] <- NA
d <- as.data.frame.table(mat, responseName="score")
d[d$score %in% 3, ]
#    Var1 Var2 score
# 22 ID_5 ID_3     3
# 47 ID_7 ID_5     3

关于r - 如何从矩阵中仅获取一个连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66507728/

相关文章:

使用字符串向量重命名选定的列

r - 提交数据到shiny创建数据框,然后将数据框写入文件

r - 当一个变量实际上是两列时 expand.grid

java - Android ACTION_MOVE图像设置图像滚动范围超出其父级

r - 将新的(较短的)列添加到 tibble 并扩展 tibble 以保持整洁

r - 使用 tidyeval 编程: tidyr::unite(col = !!col) 之后的 mutate 函数

R:ggplot在x轴上显示所有日期

r - 如何根据条件将向量元素与前一个元素粘贴在一起

python - numpy csr 矩阵 "mean"函数是否对所有矩阵求平均值?我怎样才能删除某个值?

c - 将双指针分配给矩阵