r - 计算变量运行所用的时间

标签 r

我有一个包含时间和输出列的数据文件。 输出列由值 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/

相关文章:

r - 如何在 R 中以概率方式合并两个向量

r - R 中的基于零的数组/向量

r - 如何在 R 中绘制完整的图形?

datetime - Sys.setlocale : request to set locale . ..无法兑现

r - 在 ggbiplot 中指定箭头(线段)的颜色、透明度和位置

r - 如何在ggplot2 qplot上叠加经过修改的黄土线?

R:如何从属性设置嵌套列表中的名称

r - R : is there a command for the end of a file that states whether any errors occurred?

r - 根据向量定义的多列中的值选择行

逐行应用 rvest html_nodes() 并将输出存储在新列中