我有一个带有时间和输出列的数据文件。输出列由值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
对于大数据帧来说,有什么简单的方法吗?
发布于 2016-02-17 00:50:35
听起来,您希望在每次运行输出变量的时间中,该变量等于2。
一种方法是对输出类型2的运行进行use dplyr to group by runs过滤,然后计算经过的时间:
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
发布于 2016-02-17 02:15:47
我知道你想按照前景的“运行”来分组?
首先,我们需要对“运行”进行索引。我创建了一个基于rle的函数(我找不到任何可以这样做的东西,但它可能已经存在了)。
indexer <-function(x){
run <- rle(x)$length
size <- length(run)
value <- c()
for(i in 1:size){
value = c(value, rep(i,run[i]))
}
value
}
df$index <- indexer(df$output)
df %>% group_by(index) %>% mutate(total = max(time) - min(time))
time output index total
1 2 2 1 2
2 4 2 1 2
3 6 1 2 0
4 8 2 3 2
5 10 2 3 2
6 12 1 4 4
7 14 1 4 4
8 16 1 4 4
9 18 2 5 4
10 20 2 5 4
11 22 2 5 4
https://stackoverflow.com/questions/35445780
复制相似问题