0

I got this df:

df <- data.frame(flow = c(1,2,3,4,5,6,7,8,9,10,11))

  flow
1     1
2     2
3     3
4     4
5     5
6     6
7     7
8     8
9     9
10   10
11   11

and i want to get the week average from the line we're, like this:

  flow   flow7mean
1     1          4 `(mean of 1,2,3,4,5,6,7)`
2     2          5 (mean of 2,3,4,5,6,7,8)
3     3          6 (mean of 3,4,5,6,7,8,9)
4     4          7 (mean of 4,5,6,7,8,9,10)
5     5          8 (mean of 5,6,7,8,9,10,11)
6     6          NA (it's ok, because there is just 6 flow data)
7     7          NA
8     8          NA
9     9          NA
10   10          NA
11   11          NA

i have tried some loop solutions, but i think that a vectorized solution is better

Bryan Souza
  • 497
  • 2
  • 10

3 Answers3

4

Try this using rollmean() from zoo package:

library(zoo)
#Code
df$M <- rollmean(df$flow,k = 7,align = 'left',fill=NA)

Output:

df
   flow  M
1     1  4
2     2  5
3     3  6
4     4  7
5     5  8
6     6 NA
7     7 NA
8     8 NA
9     9 NA
10   10 NA
11   11 NA
Duck
  • 39,058
  • 13
  • 42
  • 84
  • i got this error: In zoo:rollmean(Q7$Vazao, k = 7, align = "left", fill = NA) : numerical expression has 12245 elements: only the first used (my first value is NA) – Bryan Souza Oct 21 '20 at 19:05
  • @BryanSouza First try with the data you shared. Second tests this `df$M <- rollmean(df$flow,k = 7,align = 'left',fill=NA,na.rm=T)` and check the type of your variable using `str()` – Duck Oct 21 '20 at 19:08
1

We can use roll_mean from RcppRoll

library(RcppRoll)
df$flow7mean <- roll_mean(df$flow, 7, fill = NA, align = 'left')

-output

df
#   flow flow7mean
#1     1         4
#2     2         5
#3     3         6
#4     4         7
#5     5         8
#6     6        NA
#7     7        NA
#8     8        NA
#9     9        NA
#10   10        NA
#11   11        NA
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Here is a base R option using embed

within(df,flow7mean <- `length<-`(rowMeans(embed(flow,7)),length(flow)))

which gives

   flow flow7mean
1     1         4
2     2         5
3     3         6
4     4         7
5     5         8
6     6        NA
7     7        NA
8     8        NA
9     9        NA
10   10        NA
11   11        NA
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81