我有一个7000行×160列的矩阵,我想取每行20个值的平均值使其成为1值,即列平均值(1:20)=第1个新值,平均值(21:40) =第2个新值..... avg(141:160)第1行的第8个和最后一个新值,将对所有行执行相同的敌人,最后我的矩阵将为7000 x 8,即。 160/20 = 8.在R中存档这个的最快方法是什么?
例如。最后
1st 2 4 5 6 7 7 9 4
2nd 3 6 5 3 6 7 4 3
...............
7000th 5 6 7 4 5 6 7 6
我试过这个,但它太有效了!
res <- matrix(T, nrow = 7000, ncol = 8)
for (i in 1:nrow(m)){
s <- 0
k <- 1
for (j in 1:ncol(m)){
s <- s + m[i,j]
if(j %% 20 == 0){
a <- s/20
res[i,k] <- a
k <- k + 1
s <- 0
}
}
}
谢谢。
答案 0 :(得分:5)
# example - you have this already
set.seed(1) # for reproducible example
M <- matrix(rnorm(7000*160),nc=160)
# you start here...
indx <- rep(1:8,each=20)
result <- sapply(1:8,function(i)rowMeans(M[,which(indx==i)]))
head(result)
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
# [1,] 0.2127915 -0.38038950 -0.087656347 0.05933375 -0.23819112 0.03943897 -0.008970226 0.03841767
# [2,] 0.3548025 0.31491967 0.144773998 -0.05972595 -0.17191220 0.04243383 0.047314127 -0.16848104
# [3,] -0.2559990 0.35942642 0.003344486 0.23424747 0.09022379 0.58685507 -0.157652263 -0.25611335
# [4,] 0.3723693 0.23901787 -0.304657019 0.41620451 0.26005406 0.09726225 -0.434833656 0.07112657
# [5,] 0.4457805 0.08682639 0.048011727 0.15753612 0.30271061 -0.05484104 -0.103921787 -0.12066903
# [6,] -0.2823111 -0.00243217 0.055399402 0.31365508 0.17940294 0.26896135 -0.439110424 -0.30403590
答案 1 :(得分:0)
使用rowsum
和jlhoward数据的另一种方式(&#34; M&#34;):
n = 20
ans = t(rowsum(t(M), rep(seq_len(ncol(M) / n), each = n))) / n
head(ans)