取矩阵r中行的平均值 [英] take the mean of rows in a matrix r

查看:265
本文介绍了取矩阵r中行的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下深度和温度数据矩阵(855行,2列),并希望获取每列中每3行的平均值.例如:

I have the following matrix of depth and temperature data (855 rows, 2 col) and would like to take the mean of every 3 rows within each column. For example:

 [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行平均值编写代码的情况下完成此任务?任何想法或建议都将不胜感激.

for the entire matrix. How can I accomplish this without manually writing the code for the mean of every 3 rows? Any ideas or suggestions are greatly appreciated.

推荐答案

使用zoo软件包中的rollapply函数.有关更多详细信息,请参见?rollapply.

Use rollapply function from zoo package. See ?rollapply for more details.

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

如果要获取矩阵中所有列的均值,则只需在rollapply调用中添加by.column=TRUE:

If you want the mean for all columns in your matrix, then just add by.column=TRUE in the rollapply call:

> 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中行的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆