如何在 R 中执行此操作

How to do this in R

我有一个如下所示的数据集:

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

"position"列总是在2和1之间交替。我想在R中做这个计算:从第一行开始,如果它在位置1,忽略它。如果它从 2 开始(如本例),则计算如下:

期望的输出(来自示例):

    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

由于您在 position 中的值始终在 1 和 2 之间交替,您可以定义奇数行索引 i1 和偶数行索引 i2,然后进行计算:

## In case first row has position==1, we add an increment of 1 to the indexes
inc=0
if(sample.data$position[1]==1)
{inc=1}
i1=seq(1+inc,nrow(sample.data),by=2)
i2=seq(2+inc,nrow(sample.data),by=2)
res=data.frame(dA=(lead(sample.data$A[i1])+sample.data$A[i1])/2-sample.data$A[i2],
dB=(lead(sample.data$B[i1])+sample.data$B[i1])/2-sample.data$B[i2]);

这个returns:

dA  dB
1  -1.5 1.5
2  -2.0 3.5
3  -3.5 2.5
4  -4.5 2.5
5  -4.5 2.5
6  -2.5 4.0
7  -3.5 2.5
8  -3.0 3.0
9  -3.0 4.5
10   NA  NA

最后一行returns不适用,需要的可以去掉

res=na.omit(res)
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'))