Hi there!
I'm learning how to write loops. I am trying to calculate the rolling average of several columns and add them back into the original dataframe for several different sites.
The rollmean() line of code is exactly what I want it to be.
The problem I'm running into is that the current code works for one column but I can't get the rolling average for more than one column.
The final output would be the original df with two columns added titled 'roll.os' and 'roll.so4'.
Any help is appreciated. Thanks so much!
text <- "SiteNumber os SO4 Date
3 1 1 1/1/2000
3 1 1 1/2/2000
3 1 1 1/3/2000
3 2 2 1/4/2000
3 2 2 1/5/2000
3 2 2 1/6/2000
3 3 3 1/7/2000
3 3 3 1/1/2000
7 3 3 1/2/2000
7 4 4 1/3/2000
7 4 4 1/4/2000
7 4 4 1/5/2000
7 5 5 1/6/2000
7 5 5 1/7/2000
7 5 5 1/8/2000
7 6 6 1/9/2000
"
df <- read.delim(text=text, header=TRUE)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
df$Date <- mdy(df$Date)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:lubridate':
#>
#> intersect, setdiff, union
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
df <- df %>%
mutate(SiteNum = case_when(
SiteNumber == "7" ~ 1L,
SiteNumber == "3" ~ 2L,)
)
library(zoo)
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#> as.Date, as.Date.numeric
all_so4 = data.frame()
for(i in 1:2) {
site <- subset(df, df$SiteNum==i)
site$roll.so4 <- rollmean(site$SO4, 3, na.rm=TRUE , fill=NA, align="right")
all <- data.frame(site)
all_so4 <- rbind(all_so4, all)
}
# this is the final desired output
"SiteNumber os SO4 Date roll.os roll.so4
3 1 1 1/1/2000 NA NA
3 1 1 1/2/2000 NA NA
3 1 1 1/3/2000 1 1
3 2 2 1/4/2000 1.33 1.33
3 2 2 1/5/2000 1.67 1.67
3 2 2 1/6/2000 2.00 2.00
3 3 3 1/7/2000 2.33 2.33
3 3 3 1/1/2000 2.67 2.67
7 3 3 1/2/2000 NA NA
7 4 4 1/3/2000 NA NA
7 4 4 1/4/2000 3.67 3.67
7 4 4 1/5/2000 4.00 4.00
7 5 5 1/6/2000 4.33 4.33
7 5 5 1/7/2000 4.67 4.67
7 5 5 1/8/2000 5.00 5.00
7 6 6 1/9/2000 5.33 5.33
Created on 2020-06-23 by the reprex package (v0.3.0)