I have a value column 'v', grouped by an 'id' column which indicates if values are standards ('s') or collected in field (1.1 - 1.5; 2.1 - 2.5), like this:
id v
1 s 8
2 s 3
3 s 3
4 1.1 7
5 1.2 3
6 1.3 6
7 1.4 5
8 1.5 10
9 s 3
10 s 8
11 s 6
12 2.1 2
13 2.2 8
14 2.3 1
15 2.4 4
16 2.5 3
17 s 5
18 s 2
19 s 5
For each sequence of field measurements, I need to calculate the mean and standard deviation of all standard values immediately before and after the focal group of field values. Thus, for first group of field samples 1.1-1.5, I need to calculate mean and sd of 'v' for the previous (rows 1-3) and following (rows 9-11) chunks of standard values. Similarly for the second group of field samples (2.1-2.5), I need the mean and sd of standard values in rows 9-11 and 17-19.
Note that number of the samples and standards vary across datasets. They are not always in a 3-5-3-5 configuration as in this simplified example.
The desired result is:
id v v_mean v_sd
1 s 8 NA NA
2 s 3 NA NA
3 s 3 NA NA
4 1.1 7 5.17 2.48 # 5.17 = mean of previous and following run of standard values
5 1.2 3 5.17 2.48 # mean(d$v[c(1:3, 9:11)])
6 1.3 6 5.17 2.48 # 2.48 = sd of previous and following run of standard values
7 1.4 5 5.17 2.48 # sd(d$v[c(1:3, 9:11)])
8 1.5 10 5.17 2.48
9 s 3 NA NA
10 s 8 NA NA
11 s 6 NA NA
12 2.1 2 4.83 2.14 # 4.83 = mean(d$v[c(9:11, 17:19)])
13 2.2 8 4.83 2.14 # 2.14 = sd(d$v[c(9:11, 17:19)])
14 2.3 1 4.83 2.14
15 2.4 4 4.83 2.14
16 2.5 3 4.83 2.14
17 s 5 NA NA
18 s 2 NA NA
19 s 5 NA NA
These questions were helpful: How to take the mean of values between a range of rows in R? and How to take the mean of last 10 values in a column before a missing value using R?, but my problem is the continual shifting of the averages.
Data:
d = structure(list(id = c("s", "s", "s", "1.1", "1.2", "1.3","1.4", "1.5", "s", "s", "s",
"2.1", "2.2", "2.3", "2.4", "2.5", "s", "s", "s"),
v = c(8, 3, 3, 7, 3, 6, 5, 10, 3,
8, 6, 2, 8, 1, 4, 3, 5, 2, 5)),
row.names = c(NA, -19L), class = "data.frame", index = integer(0))