如何仅从矩阵建立一个连接 [英] How to take only one connection from a matrix

查看:47
本文介绍了如何仅从矩阵建立一个连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵,如下图所示

I have a matrix, like the below one

       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.table filter ,因为我只想要那些具有3的值.输出看起来像

I used as.data.frame.table and filter because I want only those values that have 3. The output look likes

  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 .

But, my actual expected output is like the below one. Because, ID_3 ID_5 3 and ID_5 ID_3 3 are same (in terms of concept). So, I want only ID_3 ID_5 3 not 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")))

推荐答案

您可以将字符串与< = 进行比较,但不能进行因素比较.因此,在过滤所有 Var1>之前,将 Var1 Var2 强制转换为字符.Var2 退出.

You can compare character strings with <= but not factors. So, coerce Var1 and Var2 to character before filtering all Var1 > Var2 out.

library(dplyr)

mat %>% as.data.frame.table(responseName = "score") %>%
  mutate(Var1 = as.character(Var1),
         Var2 = as.character(Var2)) %>%
  filter(score == 3 & Var1 <= Var2) %>%
  rename(nodeA = Var1, nodeB = Var2)
#  nodeA nodeB score
#1  ID_3  ID_5     3
#2  ID_5  ID_7     3

这篇关于如何仅从矩阵建立一个连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆