我有一个包含时间和输出列的数据文件。 输出列由值 1 和 2 组成。 对于值为 2 的输出列的每次运行,我想计算运行期间经过的总时间,即结束时间减去开始时间。例如:
time output total
2 2 4-2=2
4 2
6 1
8 2 10-8=2
10 2
12 1
14 1
16 1
18 2 22-18=4
20 2
22 2
对于大型数据框,是否有一些简单的方法可以做到这一点?
最佳答案
听起来您希望每次运行输出变量时耗时都等于 2。
一种方法是 use dplyr to group by runs ,过滤到输出类型 2 的运行,然后计算耗时:
library(dplyr)
dat %>%
group_by(run={x = rle(output) ; rep(seq_along(x$lengths), x$lengths)}) %>%
filter(output == 2) %>%
summarize(total=max(time)-min(time))
# Source: local data frame [3 x 2]
#
# run total
# (int) (dbl)
# 1 1 2
# 2 3 2
# 3 5 4
这也可以使用 rle
函数在基础 R 中完成:
x <- rle(dat$output)
unname(tapply(dat$time, rep(seq_along(x$lengths), x$lengths), function(x) max(x)-min(x))[x$values == 2])
# [1] 2 2 4
关于r - 计算变量运行所用的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35445780/