我有火车旅行的数据以及我想要计算总和的延误或取消的火车数量。
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/