Home > Software design >  how to create a function or loop that can sum a certain amount of rows above it from another column
how to create a function or loop that can sum a certain amount of rows above it from another column

Time:07-05

I am trying to calculate degree heating weeks in the Ocean and was wondering how I could create a loop or some other methods that would calculate this value and put it in a new column(DHW) for each row. DHW is a value calculated for each day.

It is calculated over a 12-week rolling window (84 days) from another column of values (hotspot). DHW is the sum of those 84 rows (value in its own row(day) plus the 83 above it) and then divided by 7

enter image description here

Below is an example of my data frame, I am just using the Hotspot column to calculate DHW

enter image description here

CodePudding user response:

if I understood correctly

fix width = 3 to width = 84

df <-
  data.frame(DAYS = seq(as.Date("2022-01-01"), length.out = 10,  by = "1 days"),
             HS = seq(10))

library(dplyr)

df %>%
  mutate(DWH = zoo::rollapply(
    HS,
    width = 3,
    FUN = function(x) sum(x) / 7,
    fill = NA,
    align = "right"
  ))
#>          DAYS HS       DWH
#> 1  2022-01-01  1        NA
#> 2  2022-01-02  2        NA
#> 3  2022-01-03  3 0.8571429
#> 4  2022-01-04  4 1.2857143
#> 5  2022-01-05  5 1.7142857
#> 6  2022-01-06  6 2.1428571
#> 7  2022-01-07  7 2.5714286
#> 8  2022-01-08  8 3.0000000
#> 9  2022-01-09  9 3.4285714
#> 10 2022-01-10 10 3.8571429

Created on 2022-07-04 by the reprex package (v2.0.1)

  • Related