簡體   English   中英

查找矩陣列的子集的行和

[英]Find row sums for a subset of the columns of a matrix

這是一個10 x 12矩陣:

mat <- matrix(runif(120, 0, 1), 10)

我試圖按行找到矩陣子集的列總和(具體地,列1到4,5到8和9到12的列和)。 期望的輸出將是10×3矩陣。

我試圖從方法這個答案使用tapplyby (與彎路rowsumaggregate ),但他們都遇到了錯誤。

OP描述的內容在R中稱為行和:

# using Matthew Lundberg's example data
x <- matrix(1:36, 3,12)

g = split(seq(ncol(x)), (seq(ncol(x)) - 1) %/% 4 )
sapply(g, function(cols) rowSums( x[, cols] ))

#       0  1   2
# [1,] 22 70 118
# [2,] 26 74 122
# [3,] 30 78 126

通常在行/觀察上有分組變量而不是列/變量。 為了達到這種情況,OP可以轉置:

rowsum( t(x), (seq(ncol(x))-1) %/% 4 )
#   [,1] [,2] [,3]
# 0   22   26   30
# 1   70   74   78
# 2  118  122  126

您可以使用強制方法執行此操作,指定apply每個列:

t(apply(x, 1, function(y) c(sum(y[1:4]), sum(y[5:8]), sum(y[9:12]))))

使用非隨機數據更容易看到,輸入的矩陣更短:

> x <- matrix(1:36, 3,12)
> x
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,]    1    4    7   10   13   16   19   22   25    28    31    34
[2,]    2    5    8   11   14   17   20   23   26    29    32    35
[3,]    3    6    9   12   15   18   21   24   27    30    33    36
> t(apply(x, 1, function(y) c(sum(y[1:4]), sum(y[5:8]), sum(y[9:12]))))
     [,1] [,2] [,3]
[1,]   22   70  118
[2,]   26   74  122
[3,]   30   78  126

您也可以分裂與向量split ,雖然這是對R更地道,更靈活,它是不是真的更可讀:

> t(apply(x, 1, function(y) sapply(split(y, ceiling(seq_along(y)/4)), sum)))
      1  2   3
[1,] 22 70 118
[2,] 26 74 122
[3,] 30 78 126

我們都可以轉換成array ,使用applyMARGIN=1 ,並獲得colSums

n <- 4
t(apply(array(mat, dim=c(nrow(mat), n, ncol(mat)/n)), 1, colSums))

或者另一種選擇是來自library(reshape2) melt/acast library(reshape2)

library(reshape2)
acast(melt(mat), Var1~(Var2-1)%/%n, value.var='value', sum)

包裝函數recast可用於使這個緊湊

recast(mat, Var1~(Var2-1)%/%4, id.var=NULL, sum)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM