【问题标题】:Sum of consecutive rows if they meet a condition满足条件的连续行的总和
【发布时间】:2018-02-06 15:39:43
【问题描述】:

我正在使用 R 分析包含干旱指数 (SPEI) 月度值的时间序列。数据结构如下:

df <- data.frame(
  spei = c(-0.52677,-0.33412, -0.89412 ,0.83459,0.65078,-0.59507,-1.16728,-1.42036,-1.47762,-1.73324,-1.23006,-1.10954), 
  month = c(7:12, 1:6), 
  year = c(rep(1992, 6), rep(1993, 6))
)

我想根据这个定义获得干旱事件的持续时间:指数(spei)低于某个阈值(本例中为-0.86)的连续月数。

有什么帮助吗?

【问题讨论】:

  • 这个例子的预期输出是什么?

标签: r


【解决方案1】:

以下是我解决问题的方法。我们使用来自rle 的结果来找出当前的连续多长时间(使用来自rlelengths),然后我们使用来自valueslengthsrle 创建一个drought 变量:

r_l <- rle(df$spei <= -.86) #runs of drought variable

(drought_df <- data.frame(streak = unlist(sapply(r_l$lengths, FUN = function(x) 1:x)),
           drought = rep(r_l$values, r_l$lengths),
           stringsAsFactors = FALSE))

   streak drought
1       1   FALSE
2       2   FALSE
3       1    TRUE
4       1   FALSE
5       2   FALSE
6       3   FALSE
7       1    TRUE
8       2    TRUE
9       3    TRUE
10      4    TRUE
11      5    TRUE
12      6    TRUE

然后你可以cbind 回到原来的表:

cbind(df, drought_df)

       spei month year streak drought
1  -0.52677     7 1992      1   FALSE
2  -0.33412     8 1992      2   FALSE
3  -0.89412     9 1992      1    TRUE
4   0.83459    10 1992      1   FALSE
5   0.65078    11 1992      2   FALSE
6  -0.59507    12 1992      3   FALSE
7  -1.16728     1 1993      1    TRUE
8  -1.42036     2 1993      2    TRUE
9  -1.47762     3 1993      3    TRUE
10 -1.73324     4 1993      4    TRUE
11 -1.23006     5 1993      5    TRUE
12 -1.10954     6 1993      6    TRUE

编辑

如果您只想要最长的连续干旱,您可以使用:

max(subset(drought_df, drought)$streak) # subset drought_df for only drought periods
[1] 6

【讨论】:

  • 我投了赞成票,但我认为他真的只是想要max(rle(df$spei &lt;= -.86)$lengths)
  • 我添加了一个允许这种计算的编辑。谢谢
  • @Moody_Mudskipper 但是,当他想要所有的干旱运行时,那不是只会给出最大的干旱运行吗?快速修改代码:rle(df$spei &lt;= -.86)$lengths[rle(df$spei &lt;= -.86)$value]
  • @Lyngbakr 这比必要的更脏。我的编辑是(IMO)更清洁的方式
  • OP 会在必要时澄清 ;)
【解决方案2】:

我仍然不知道预期的结果,但这也可能会提供一些见解:

 transform(df,drought=ave(x<-spei<=-0.86, cumsum(!x), FUN = cumsum))
       spei month year drought
1  -0.52677     7 1992       0
2  -0.33412     8 1992       0
3  -0.89412     9 1992       1
4   0.83459    10 1992       0
5   0.65078    11 1992       0
6  -0.59507    12 1992       0
7  -1.16728     1 1993       1
8  -1.42036     2 1993       2
9  -1.47762     3 1993       3
10 -1.73324     4 1993       4
11 -1.23006     5 1993       5
12 -1.10954     6 1993       6

【讨论】:

    猜你喜欢
    • 2022-07-22
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多