r中的双条件数据选择

时间:2014-09-16 12:10:47

标签: r sum range selection

我使用聚合 pylr 等函数广泛阅读有关条件的选择,但我的情况似乎没问题。

我确信编程并不困难,但我想要一些意见。 基本上如何开始,你将遵循什么样的推理线。

感谢您的任何建议。

所以我的简化数据集看起来像这样

time.stamp <- c(21.0,21.1,21.2,21.3,21.4)
behavior <- c("close", "1", "close","1","close")
event_type <- c("start","point","stop","point","start")

example <- data.frame(time.stamp,behavior,event_type)



  time.stamp behavior event_type
1       21.0    close      start
2       21.1        1      point
3       21.2    close       stop
4       21.3        1      point
5       21.4    close      start

我的研究问题是:行为中的行为数= = 1 = =关闭。

例如,在这种情况下答案是1 因为第二个1是在关闭和停止之后。

在其他可能的解决方案中,我考虑按时间范围进行子集化。在关闭和开始之间以及关闭和停止之间的时间戳,但我不知道如何在代码中翻译它。

正如我所说,我希望得到关于如何思考问题的一些意见。

非常感谢, 我希望学到一些东西。 干杯

2 个答案:

答案 0 :(得分:0)

我会这样做:

n = nrow(example)
length(which(example$behavior[2:n]==1 & example$event_type[1:n-1]!= "stop"))

答案 1 :(得分:0)

我想解决这个问题,你不需要任何特殊的套餐。仅使用&#39; base&#39;:

length( which( example$behavior[which( example$behavior == 'close' & as.character(example$event_type) == 'stop')+1] == 1 ) )

编辑:清除所需输出后,代码更改为:

sum((which( example$behavior == 'close' & as.character(example$event_type) == 'stop') - which( example$behavior == 'close' & as.character(example$event_type) == 'start')) - 1)

最佳, ADII _