Question

I would like to average pairs of columns in a data set, not with a moving average. I want to divide up the columns into groups of two and find the average for each pair.

I present a sample data set, the desired result, and nested for-loops that return the desired result. I just thought there is likely a better way. Sorry if I have overlooked the solution in a different post. I did search here, but I did not search the internet as diligently as I usually attempt. Thank you for any advice.

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) 

  }
}
Was it helpful?

Solution

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

Then you can add the first column to the output matrix.

output <- cbind(x[,1], output)

Alternatively, you can use within:

within(x, {
    pair.colmeans <- sapply(seq(2, ncol(x), 2), function(i) {
        rowMeans(x[, c(i, i+1)], na.rm=TRUE)
    })
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top