【问题标题】:R - finding pattern in a column and replacing it (more efficient solution)R - 在列中查找模式并替换它(更有效的解决方案)
【发布时间】:2019-04-04 05:48:44
【问题描述】:

我有每条路线的大量乘客数据集,类似于以下内容:

routes <- c("MEX-GDL", "ACA-MEX", "CUN-MTY", "MTY-CUN", "GDL-MEX", "MEX-ACA")
pax <- sample(100:500, size = 6, replace = T)
traffic <- data.frame(routes = routes, pax = pax)

   routes pax
   1 MEX-GDL 282
   2 ACA-MEX 428
   3 CUN-MTY 350
   4 MTY-CUN 412
   5 GDL-MEX 474
   6 MEX-ACA 263

如果出发地和目的地匹配,我想对航班进行分组以获得路线中的乘客总数 - 例如,将路线 MEX-GDL 重命名为 GDL-MEX 或反之亦然,这样我就可以使用 group_by() on数据集。

有点像这样:

traffic %>% group_by(routes) %>% summarise(sum(pax)) 

我已经完成了以下操作并且它有效,但我相信可以有一种更有效的方法来解决问题(因为它需要相当长的时间来运行):

library(tidyverse)

traffic$routes <- as.character(traffic$routes)

for(route in traffic$routes){
  a <- substring(route, first = 1, last = 3) 
  b <- substring(route, first = 5, last = 7)
  aux <- which(sapply(traffic$routes, str_detect, pattern = paste0(b,"-",a)))
  traffic$routes[aux] <- paste0(a,"-",b)
}

有什么建议吗?

感谢您的帮助!

注意:这是我在这里的第一个问题,所以我希望我遵守了所有准则。

【问题讨论】:

  • 第一个问题很好!如果只有所有新用户都能做到这一点:)

标签: r substring sapply


【解决方案1】:

我们可以将separate分成两列,按pmaxpmin分组,得到sum

library(tidyverse)
traffic %>% 
   separate(routes, into = c("Col1", "Col2")) %>%
   group_by(ColN = pmin(Col1, Col2), ColN2 = pmax(Col1, Col2)) %>% 
   summarise(Sum = sum(pax))

【讨论】:

    【解决方案2】:

    data.table版本

    数据:(?IREAD THIS)

    traffic <- data.frame(routes = I(routes), pax = pax)
    
    library(data.table)
    setDT(traffic)[,routes := sapply(strsplit(routes, split="-"), function(x) paste0(sort(x),collapse = "-"))][,.(Sum = sum(pax)), by = routes]
    

    结果:(值因sample 函数而不同)

    #    routes Sum
    #1: GDL-MEX 621
    #2: ACA-MEX 595
    #3: CUN-MTY 266
    

    • 如果您使用带有?sample 的数据,请同时使用?set.seed

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 2012-10-20
      • 1970-01-01
      • 2021-05-06
      • 2016-06-27
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多