R - 如何按年份使用累积总和并在满足条件时重新启动累积总和

标签 r dataframe sum restart counting

我在 R 中有以下数据框:

  YEAR DOY   PRECTOT cumsum Lws   prec0
   <int> <chr>   <dbl>  <dbl> <chr> <chr>
 1  1982 121    6.05     6.05 no    no   
 2  1982 122    1.10     7.15 no    no   
 3  1982 123    0.490    7.64 no    no   
 4  1982 124    4.53    12.2  no    no   
 5  1982 125    3.94    16.1  no    no   
 6  1982 126    2.78    18.9  no    no   
 7  1982 127    0.420   19.3  no    no   
 8  1982 128    0.      19.3  no    yes  
 9  1982 129    0.0700  19.4  no    no   
10  1982 130    8.94    28.3  no    no 

我想要另一列计算累积总和,就像在 cumsum 列中一样,但是当 PRECTOT 为 0 时重新开始计数,例如在第 8 行。基本上它应该从第 8 行重新开始累积总和,并从那里继续累积总和,因此:
  YEAR DOY   PRECTOT cumsum Lws   prec0
   <int> <chr>   <dbl>  <dbl> <chr> <chr>
 1  1982 121    6.05     6.05 no    no   
 2  1982 122    1.10     7.15 no    no   
 3  1982 123    0.490    7.64 no    no   
 4  1982 124    4.53    12.2  no    no   
 5  1982 125    3.94    16.1  no    no   
 6  1982 126    2.78    18.9  no    no   
 7  1982 127    0.420   19.3  no    no   
 8  1982 128    0.      0  no    yes  
 9  1982 129    0.0700  0.0700  no    no   

在 R 中是否有一种很好且有效的方法?谢谢你。

最佳答案

“满足条件时重新启动”部分是用 group_by(cumsum(<condition>)) 完成的。 :

library(dplyr)

dat %>% 
  group_by(grp = cumsum(PRECTOT == 0)) %>% 
  mutate(cumsum = cumsum(PRECTOT))

# # A tibble: 10 x 7
# # Groups:   grp [2]
#     YEAR DOY   PRECTOT cumsum Lws   prec0   grp
#    <int> <chr>   <dbl>  <dbl> <chr> <chr> <int>
#  1  1982 121      6.05   6.05 no    no        0
#  2  1982 122      1.1    7.15 no    no        0
#  3  1982 123      0.49   7.64 no    no        0
#  4  1982 124      4.53  12.2  no    no        0
#  5  1982 125      3.94  16.1  no    no        0
#  6  1982 126      2.78  18.9  no    no        0
#  7  1982 127      0.42  19.3  no    no        0
#  8  1982 128      0      0    no    yes       1
#  9  1982 129      0.07   0.07 no    no        1
# 10  1982 130      8.94   9.01 no    no        1

数据:
dat <- readr::read_table2(
"YEAR DOY   PRECTOT cumsum Lws   prec0
1982 121    6.05     6.05 no    no
1982 122    1.10     7.15 no    no
1982 123    0.490    7.64 no    no
1982 124    4.53    12.2  no    no
1982 125    3.94    16.1  no    no
1982 126    2.78    18.9  no    no
1982 127    0.420   19.3  no    no
1982 128    0.      19.3  no    yes
1982 129    0.0700  19.4  no    no
1982 130    8.94    28.3  no    no
", col_types = "icddcc")

关于R - 如何按年份使用累积总和并在满足条件时重新启动累积总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50696176/

相关文章:

python - 如何根据行的内容分割pyspark数据帧

java - 如何通过java找到存储在XML文件中的节点值的总和?

html - R Shiny : Add weblink to actionButton

r - 可以在不声明变量的情况下命名它吗?

r - 如何在 64 位 Windows 计算机上安装 rJava 以与 64 位 R 一起使用?

r - 将两个数据框的行(按列名合并)与重复的列名绑定(bind)

python - 计算满足条件的连续值的数量(Pandas Dataframe)

mysql - 计算用户点 - 更新与选择

php - 在 php 变量中添加 html 文本框值

R:使用带插入符号的 Ranger、tuneGrid 参数