Q:

How to do this in R

I have a dataset that looks like this:
groups <- c(1:20)
A <- c(1,3,2,4,2,5,1,6,2,7,3,5,2,6,3,5,1,5,3,4)
B <- c(3,2,4,1,5,2,4,1,3,2,6,1,4,2,5,3,7,1,4,2)
position <- c(2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1)
sample.data <- data.frame(groups,A,B,position)
head(sample.data)
      groups     A       B     position
  1      1       1       3        2
  2      2       3       2        1
  3      3       2       4        2
  4      4       4       1        1
  5      5       2       5        2
  6      6       5       2        1

The "position" column always alternates between 2 and 1.  I want to do this calculation in R: starting from the first row, if it's in position 1, ignore it.  If it starts at 2 (as in this example), then calculate as follows: 

Take the first 2 values of column A that are at position 2, average them, then subtract the first value that is at position 1 (in this example: (1+2)/2 - 3 = -1.5).  Then repeat the calculation for the next set of values, using the last position 2 value as the starting point, i.e. the next calculation would be (2+2)/2 - 4 = -2.  
So basically, in this example, the calculations are done for the values of these sets of groups: 1-2-3, 3-4-5, 5-6-7, etc. ( the last value of the previous is the first value of the next set of calculation)
Repeat the calculation until the end.  Also do the same for column B.
Since I need the original data frame intact, put the newly calculated values in a new data frame(s), with columns dA and dB corresponding to the calculated values of column A and B, respectively (if not possible then they can be created as separated data frames, and I will extract them into one afterwards). 

Desired output (from the example):
    dA    dB
1  -1.5  1.5
2   -2   3.5
3  -3.5  2.5
4  -4.5  2.5
5  -4.5  2.5
6  -2.5   4

A:

groups <- c(1:20)
A <- c(1,3,2,4,2,5,1,6,2,7,3,5,2,6,3,5,1,5,3,4)
B <- c(3,2,4,1,5,2,4,1,3,2,6,1,4,2,5,3,7,1,4,2)
position <- c(2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1)
sample.data <- data.frame(groups,A,B,position)

start <- match(2, sample.data$position)
twos <- seq(from = start, to = nrow(sample.data), by = 2)

df <- 
  sapply(c("A", "B"), function(l) {
    sapply(twos, function(i) { 
      mean(sample.data[c(i, i+2), l]) - sample.data[i+1, l]
    })
  })

df <- setNames(as.data.frame(df), c('dA', 'dB'))

