R 中的平均列对

Mar*_*ler 2 r sapply

我想对数据集中的列对进行平均,而不是使用移动平均线。我想将列分成两组,并找到每对的平均值。

我提供了一个示例数据集、所需的结果以及返回所需结果的嵌套 for 循环。我只是认为可能有更好的方法。抱歉,如果我忽略了另一篇文章中的解决方案。我确实在这里搜索过,但我没有像平时那样勤奋地搜索互联网。感谢您的任何建议。

x = read.table(text = "
  site     yr1  yr2  yr3  yr4
    1       2    4    6    8
    2      10   20   30   40
    3       5   NA    2    3
    4     100  100   NA   NA", 
sep = "", header = TRUE)

x

desired.outcome = read.table(text = "
  site    ave12  ave34
    1       3      7
    2      15     35
    3       5    2.5
    4     100     NA", 
sep = "", header = TRUE)

result <- matrix(NA, ncol=((ncol(x)/2)+1), nrow=nrow(x))

for(i in 1: ((ncol(x)-1)/2)) {
  for(j in 1:nrow(x)) {

     result[j,   1 ] <- x[j,1]
     result[j,(i+1)] <- mean(c(x[j,(1 + ((i-1)*2 + 1))], x[j,(1 + ((i-1)*2 + 2))]), na.rm = TRUE) 

  }
}
Run Code Online (Sandbox Code Playgroud)

DrD*_*Dom 5

output <- sapply(seq(2,ncol(x),2), function(i) {
  rowMeans(x[,c(i, i+1)], na.rm=T)
})
Run Code Online (Sandbox Code Playgroud)

然后您可以将第一列添加到output矩阵中。

output <- cbind(x[,1], output)
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用within

within(x, {
    pair.colmeans <- sapply(seq(2, ncol(x), 2), function(i) {
        rowMeans(x[, c(i, i+1)], na.rm=TRUE)
    })
})
Run Code Online (Sandbox Code Playgroud)