有没有一种方法可以根据R数据帧相邻行中的值来操作R数据帧行



我正在研究一个建模种群的指标,它在一定程度上随机上升和下降,如果它在一两年内超过设定的限制,这不是问题,但如果它在几年内超过限制,这表明种群出了问题。

我有一些数据帧,其中的值可以在一个时间序列(t(的一个设定限制内(not_out(或外(out(。我想提取t的第一个实例,其中值为"out"的行数超过了一组,例如3。例如

set.seed(36)
example.data <- data.frame("t" = c(1:15) , 
"value" = sample(-3:3, 15, replace = TRUE), 
"limit" = 2)
example.data <- mutate(example.data, 
"out_" = ifelse(value >= limit | value <= 0 - limit, "out", "not_out"))
example.data
t value limit    out_
1   1     1     2 not_out
2   2     2     2     out
3   3    -1     2 not_out
4   4     0     2 not_out
5   5    -3     2     out
6   6     3     2     out
7   7    -2     2     out
8   8     0     2 not_out
9   9     3     2     out
10 10     1     2 not_out
11 11     1     2 not_out
12 12     3     2     out
13 13     3     2     out
14 14     0     2 not_out
15 15     0     2 not_out

因此,t=5将是第一个值"out"并保持"out"超过3行的实例。

我试着用for循环和if语句来解决这个问题。。。

for(t in min(example.data$t) : max(example.data$t)) {

if(example.data$out_ == "out"){
a <- t
return(a)
}

}

但我正在努力让它为out_=="的一个实例工作;"out";,我不知道如何告诉R我希望它看起来像t&t+1…t+n。如有任何帮助,我们将不胜感激。

您也可以使用data.table,如下所示:

library(data.table)
d <- as.data.table(example.data)
d[, n.prev.out := (shift(out_, type = 'lag', n = 1) == "out" &
shift(out_, type = 'lag', n = 2) == "out" &
out_ == "out")]
example.data %>%
group_by(grp = data.table::rleid(out_)) %>%
filter(row_number() == 1 & out_ == "out" & n() > 3) %>%
ungroup() %>%
select(-grp)

最新更新