gpt4 book ai didi

r - R中的平均列对

转载 作者:行者123 更新时间:2023-12-02 22:20:46 25 4
gpt4 key购买 nike

我想平均数据集中的列对,而不是移动平均数。我想将列分成两组,并找出每组的平均值。

我展示了一个示例数据集、所需的结果以及返回所需结果的嵌套 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)

}
}

最佳答案

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

然后您可以将第一列添加到输出矩阵。

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

或者,您可以使用 within:

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

关于r - R中的平均列对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13739243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com