For each row of column "Response", I would like to check if the 5 rows below it have "Response"-values (i.e. have no NAs) and if so, then I would like to calculate the mean and standard deviation of those 5 rows below. If any row, in those 5 rows below, has a missing "Response"-value (i.e. NA), then the final output should be "NA" (since I want the means and stdev to be calculated for n=5 points/values).
A sample of the Input.data looks like this:
Response
NA
1
2
3
NA
1
1
2
3
4
5
Here is the code I tried, which did not give the right solution:
Input.data$count.lag <- rollapplyr(Input.data[,c("Response")],list(-(4:0)),length, fill=NA)
Input.data$stdev <- ifelse(Input.data$count.lag <5, "NA",
rollapplyr(Input.data[,c("Response")],list(-(4:0)),sd,fill=NA))
Input.data$mean <- ifelse(Input.data$count.lag <5, "NA",
rollapplyr(Input.data[,c("Response")],list(-(4:0)),mean,fill=NA))
it gave the following, which was not what I am after:
Response count.lag stdev mean
NA NA NA NA
1 NA NA NA
2 NA NA NA
3 NA NA NA
NA 5 NA NA
1 5 NA NA
1 5 NA NA
2 5 NA NA
3 5 NA NA
4 5 1.303840 2.2
5 5 1.581139 3.0
This is how the output should have been:
Response count.lag stdev mean
NA 4 NA NA
1 4 NA NA
2 4 NA NA
3 4 NA NA
NA 5 1.303840 2.2
1 5 1.581139 3.0
1 5 1.581139 4.0
2 5 1.581139 5.0
3 5 1.581139 6.0
4 5 1.581139 7.0
5 5 1.581139 8.0
Can someone please suggest where the errors are and/or an alternative solution that works? Thank you!