R中的平均列对 [英] average pairs of columns in R
问题描述
我想对数据集中的列对求平均值,而不是使用移动平均值.我想将列分成两组,并找出每对的平均值.
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.
我提供了一个示例数据集、所需的结果以及返回所需结果的嵌套 for 循环.我只是认为可能有更好的方法.抱歉,如果我忽略了另一篇文章中的解决方案.我确实在这里搜索过,但我没有像往常那样努力地在互联网上搜索.感谢您的任何建议.
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)
}
}
推荐答案
output <- sapply(seq(2,ncol(x),2), function(i) {
rowMeans(x[,c(i, i+1)], na.rm=T)
})
然后您可以将第一列添加到 output
矩阵中.
Then you can add the first column to the output
matrix.
output <- cbind(x[,1], output)
或者,您可以在内
使用:
within(x, {
pair.colmeans <- sapply(seq(2, ncol(x), 2), function(i) {
rowMeans(x[, c(i, i+1)], na.rm=TRUE)
})
})
这篇关于R中的平均列对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!