【问题标题】:How to check combinations or matches across different rows in a tibble?如何检查 tibble 中不同行的组合或匹配?
【发布时间】:2022-12-14 10:27:42
【问题描述】:

我有一个像这样的大文件:

library(tidyverse)

test <- structure(list(one = c(5014, 5014, 5014, 5033, 5033, 5033, 5040, 
5040, 5040, 5171, 5171, 5171, 5174, 5174, 5174, 5183, 5183, 5183, 
5193, 5193, 5193, 5304, 5304, 5304), two = c(5033, 5040, 5304, 
5014, 5040, 5304, 5014, 5033, 5304, 5174, 5183, 5331, 5171, 5183, 
5331, 5171, 5174, 5331, 5161, 1538, 5190, 5014, 5033, 5040)), row.names = c(NA, 
-24L), class = c("tbl_df", "tbl", "data.frame"))

两列中的数字以(递归?)方式与其他数字匹配(抱歉,我不知道如何更好地解释它)。在这个例子中,很明显(对于人类,而不是计算机)只有三个组。我怎样才能分开这些组?

我只需要这样的东西:

群号
1 5014
1 5033
1 5040
1 5304
2 5171
2 5174
2 5183
2 5331
3 5193
3 5161
3 1538
3 5190

我想有多个自连接是可能的,但这似乎非常乏味......

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    igraph

    library(igraph)
    graph_from_data_frame(test) |>
      components() |>
      getElement("membership") |>
      stack() |>
      arrange(values)
    

    输出

       values  ind
    1       1 5014
    2       1 5033
    3       1 5040
    4       1 5304
    5       2 5171
    6       2 5174
    7       2 5183
    8       2 5331
    9       3 5193
    10      3 5161
    11      3 1538
    12      3 5190
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多