【问题标题】:Iterate through grouped rows to get different pair combinations遍历分组的行以获得不同的对组合
【发布时间】:2018-10-29 14:22:53
【问题描述】:

有下表:

read.table(text = "route origin dest seq
    1   a b 1
    1   b c 2
    1   c d 3
    1   d e 4
    2   f g 1
    2   g h 2
    2   h i 3", header = TRUE)

我正在尝试找到一种遍历每一行的方法,按路线分组,并迭代每个可能的起始目的地对组合,同时考虑到 seq 变量和提到的路线。

输出应该是这样的:

  origin   dest
    a       b 
    a       c 
    a       d 
    a       e 
    b       c
    b       d
  (...)   (...)

这背后的想法是火车,例如路线 1,从 a 到 e。但是,我想列出所有可能的火车对。我尝试使用 igraph 但没有成功。 dplyr 有什么想法吗?

【问题讨论】:

  • 根据您的输入,您希望在预期输出中有多少行
  • 试试library(tidyverse); expand(df1, route, origin, dest)
  • @akrun 好吧,我希望路线 1 为 9。因此,起点和终点的组合始终是下一行的终点。 expand 的问题是它一直到表的末尾并且由于某种奇怪的原因没有考虑到组。
  • @FilipeTeixeira,你确定吗?我认为路线 1 是 10?
  • @PKumar 你说得对,现在是 10 点。我只是有点睡眠不足。

标签: r dplyr iteration


【解决方案1】:
library(dplyr)
library(tidyr)

df %>%
  mutate_if(is.factor, as.character) %>%    #convert factor variable to character
  group_by(route) %>%
  expand(origin = paste(origin, seq, sep = "_"), dest = paste(dest, seq, sep = "_")) %>%    #all possible combination of origin & destination grouped by route
  rowwise() %>%
  filter(strsplit(origin, split = "_")[[1]][1] != strsplit(dest, split = "_")[[1]][1] & 
           strsplit(origin, split = "_")[[1]][2] <= strsplit(dest, split = "_")[[1]][2]) %>%
  mutate(origin = gsub("_.*$", "", origin),
         dest   = gsub("_.*$", "", dest))

输出为:

   route origin dest 
 1     1 a      b    
 2     1 a      c    
 3     1 a      d    
 4     1 a      e    
 5     1 b      c    
...

样本数据:

df <- structure(list(route = c(1L, 1L, 1L, 1L, 2L, 2L, 2L), origin = structure(1:7, .Label = c("a", 
"b", "c", "d", "f", "g", "h"), class = "factor"), dest = structure(1:7, .Label = c("b", 
"c", "d", "e", "g", "h", "i"), class = "factor"), seq = c(1L, 
2L, 3L, 4L, 1L, 2L, 3L)), class = "data.frame", row.names = c(NA, 
-7L))

#  route origin dest seq
#1     1      a    b   1
#2     1      b    c   2
#3     1      c    d   3
#4     1      d    e   4
#5     2      f    g   1
#6     2      g    h   2
#7     2      h    i   3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    相关资源
    最近更新 更多