I need to adjust a code, which works perfectly with my dataframe (but with another set up), in order to select a 2 days time window from the column Day. In particular I am interested in the 1 day prior day0 (i.e. i - 1 and i, where i is the day of interest) and its (i - 1) values contained in the column Count have to be added into the day 0 (i) col Count.
Here an example of my dataframe:
df <- read.table(text = "
Station Day Count
1 33012 12448 4
2 35004 12448 4
3 35008 12448 4
4 37006 12448 4
5 21009 4835 3
6 24005 4835 3
7 27001 4835 3
8 25005 12447 3
9 29001 12447 3
10 29002 12447 3
11 29002 12446 3
12 30001 12446 3
13 31002 12446 3
14 47007 4834 2
15 49002 4834 2
16 47004 12445 1
17 51001 12449 1
18 51003 4832 1
19 52004 4836 1", header = TRUE)
my output should be:
Station Day Count
1 33012 12448 7
2 35004 12448 7
3 35008 12448 7
4 37006 12448 7
5 21009 4835 5
6 24005 4835 5
7 27001 4835 5
8 29002 12446 4
9 30001 12446 4
10 31002 12446 4
11 51001 12449 1
12 51003 4832 1
13 52004 4836 1
14 25005 12447 0
15 29001 12447 0
16 29002 12447 0
17 47007 4834 0
18 49002 4834 0
19 47004 12445 0
I am trying this code, but it doesn't work with my real dataframe:
for (i in unique(df$Day)) {
temp <- df$Count[df$Day == i]
if(length(temp > 0)) {
condition1 <- df$Day == i - 1
if (any(condition1)) {
df$Count[df$Day == i] <- mean(df$Count[condition1]) + df$Count[df$Day == i]
df$Count[condition1] <- 0
}
}
}
The code seems right and it has sense but my output is not.
Can anyone helps me?
@aichao code works good.
In the case that I want to consider the previous 30 days (i.e. day-30, day-29, day-28, ...., day-1, day0) is there any quick way to do it, instead of creating 30 if statements (conditions)?
Thanks again @aichao for your help.