gpt4 book ai didi

r - 取矩阵 r 中行的平均值

转载 作者:行者123 更新时间:2023-12-01 08:09:49 33 4
gpt4 key购买 nike

我有以下深度和温度数据矩阵(855 行,2 列),并且想取每列中每 3 行的平均值。例如:

 [1,]  -6.7 18.91
[2,] -5.4 18.91
[3,] -4.0 18.59
[4,] -6.7 20.37
[5,] -6.7 20.05
[6,] -2.7 20.21
[7,] -4.0 21.03
[8,] -5.4 20.70
[9,] -4.0 20.87
[10,] -2.7 21.37
[11,] -2.7 21.37
[12,] -2.7 21.37

mean(data[1:3,1])
mean(data[4:6,1])

对于整个矩阵。如何在不手动编写每 3 行平均值的代码的情况下完成此操作?非常感谢任何想法或建议。

最佳答案

使用 rollapply动物园包中的功能。见?rollapply更多细节。

library(zoo)
rollapply(matrix[,1], width=3, mean, by=3)

例子:
> set.seed(1)
> Data <- matrix(rnorm(30, 100, 50), ncol=2) # some random data
> rollapply(Data[,1], width=3, mean, by=3)
[1] 78.69268 118.40534 130.02559 126.60393 71.48317
> # you could check this out by doing some verification as in:
> mean(Data[1:3, 1])
[1] 78.69268
> mean(Data[4:6, 1])
[1] 118.4053
> mean(Data[7:9, 1]) # and so on ...
[1] 130.0256

如果您想要矩阵中所有列的均值,只需添加 by.column=TRUErollapply称呼:
> rollapply(Data, width=3, mean, by=3, by.colum=TRUE)
[,1] [,2]
[1,] 78.69268 114.71187
[2,] 118.40534 138.90166
[3,] 130.02559 81.12249
[4,] 126.60393 106.79836
[5,] 71.48317 74.48399

关于r - 取矩阵 r 中行的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14987686/

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