回程数据的 R 组列

标签 r summarize columnsorting group

我有火车旅行的数据以及我想要计算总和的延误或取消的火车数量。

Start     End        Delayed Cancelled
Paris     Rome       1       0
Brussels  Berlin     4       6
Berlin    Brussels   6       2
Rome      Paris      2       1

我如何将“开始”和“结束”列组合在一起,得出巴黎-罗马和罗马-巴黎以及布鲁塞尔-柏林和柏林-布鲁塞尔的总和,得出火车延误和取消的总行程数?

最佳答案

额外的解决方案

整洁宇宙

library(tidyverse)

df <- data.frame(
  stringsAsFactors = FALSE,
             Start = c("Paris", "Brussels", "Berlin", "Rome"),
               End = c("Rome", "Berlin", "Brussels", "Paris"),
           Delayed = c(1L, 4L, 6L, 2L),
         Cancelled = c(0L, 6L, 2L, 1L)
)

df %>% 
  rowwise() %>% 
  mutate(route = paste0(sort(c_across(c(Start, End))), collapse = "-")) %>% 
  group_by(route) %>% 
  summarise(across(where(is.numeric), sum, na.rm = TRUE))


#> # A tibble: 2 × 3
#>   route           Delayed Cancelled
#>   <chr>             <int>     <int>
#> 1 Berlin-Brussels      10         8
#> 2 Paris-Rome            3         1

reprex package 创建于 2022-04-26 (v2.0.1)

基础

df$route <- apply(df[c("Start", "End")], 1, function(x) paste0(sort(x), collapse = "-"))

aggregate(x = df[c("Delayed", "Cancelled")], by = list(df$route), FUN = sum, na.rm = TRUE)
#>           Group.1 Delayed Cancelled
#> 1 Berlin-Brussels      10         8
#> 2      Paris-Rome       3         1

reprex package 创建于 2022-04-26 (v2.0.1)

数据表

df$route <- apply(df[c("Start", "End")], 1, function(x) paste0(sort(x), collapse = "-"))

library(data.table)
setDT(df)[, lapply(.SD, sum, na.rm = TRUE), by = route, .SDcols = is.numeric]
#>              route Delayed Cancelled
#> 1:      Paris-Rome       3         1
#> 2: Berlin-Brussels      10         8

reprex package 创建于 2022-04-26 (v2.0.1)

关于回程数据的 R 组列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72015103/

相关文章:

javascript - DataTables - 1.10 中的非英文字母排序

r - 跨多个变量的总计数

MYSQL-排序varchar列包括number和char

r - 为什么 string::str_split 在 dplyr::mutate 时不更新数据帧

r - 带 R 的多彩标题

使用 R margins 包复制 Stata marginlist 参数?

R 聚合使用相同数据的子集给出不同结构的结果

r - R 中 dplyr 汇总数据帧的算术

r - 汇总必须分组的多个列 tidyverse

javascript - 在 Node.JS 中排序数据