问题描述
我有以下数据:
library(dplyr,warn.conflicts = FALSE)
df <- tibble(
x = c(30,60,90,30,90),phase = c(rep(c("phase 1","phase 2"),each = 3))
)
df
#> # A tibble: 6 x 2
#> x phase
#> <dbl> <chr>
#> 1 30 phase 1
#> 2 60 phase 1
#> 3 90 phase 1
#> 4 30 phase 2
#> 5 60 phase 2
#> 6 90 phase 2
由reprex package(v0.3.0)于2020-08-11创建
其中x
是每个phase
中经过的时间(以秒为单位)。由于phase
是连续发生的事情,因此我对计算总经过时间很感兴趣。
所需的输出:
#> # A tibble: 6 x 3
#> x phase elapsed_time
#> <dbl> <chr> <dbl>
#> 1 30 phase 1 30
#> 2 60 phase 1 60
#> 3 90 phase 1 90
#> 4 30 phase 2 120
#> 5 60 phase 2 150
#> 6 90 phase 2 180
有什么想法吗?请注意,我的实际示例具有更多的阶段。
解决方法
我相信以下帖子为您提供了答案:
How to add a cumulative column to an R dataframe using dplyr?
它显示了如何使用group_by
和mutate
创建累积列。看来您希望两个阶段的经过时间相加,因此只需在代码中不包括group_by
调用即可。
这是一个通过dplyr
的想法。首先,我们需要按phase
分组,并获取每个时间差。然后,我们ungroup()
并将cumsum()
总计,即
library(dplyr)
df %>%
group_by(phase) %>%
mutate(diffs = x - lag(x,default = 0)) %>%
ungroup() %>%
mutate(res = cumsum(diffs)) %>%
select(-diffs)
# A tibble: 6 x 3
# x phase res
# <dbl> <chr> <dbl>
#1 30 phase 1 30
#2 60 phase 1 60
#3 90 phase 1 90
#4 30 phase 2 120
#5 60 phase 2 150
#6 90 phase 2 180
,
这是另一个dplyr
解决方案。它找到每个阶段的开始,并将其添加到x
library(tidyverse)
df <- tibble(
x = c(30,60,90,30,90),phase = c(rep(c("phase 1","phase 2"),each = 3))
)
df %>% group_by(phase) %>%
nest() %>%
mutate(start = map_dbl(data,max)) %>%
ungroup() %>%
mutate(start = lag(start,default = 0)) %>%
unnest(data) %>%
mutate(elapsed_time = start + x) %>%
select(-start)
#> # A tibble: 6 x 3
#> phase x elapsed_time
#> <chr> <dbl> <dbl>
#> 1 phase 1 30 30
#> 2 phase 1 60 60
#> 3 phase 1 90 90
#> 4 phase 2 30 120
#> 5 phase 2 60 150
#> 6 phase 2 90 180
由reprex package(v0.3.0)于2020-08-11创建