2013-07-12 27 views
2

我遇到了问题,但我确定对于非常熟悉R的人来说这非常容易。 我有一个3008 x 3008的矩阵。我想要的是总计每行8列。所以基本上你会最终有一个新的矩阵,现在是367 X 367R对每行中的某些列进行求和

这里有一个小例子:

  C.1 C.2 C.3 C.4 C.5 C.6 
    row1 1 2 1 2 5 6 
    row1 1 2 3 4 5 6 
    row1 2 6 3 4 5 6 
    row1 1 2 3 4 10 6 

所以说,我想在每一行中总结这些,每3列,我倒是想落得:

  C.1 C.2 
    row1 4 13 
    row1 6 15 
    row1 11 15 
    row1 6 20 

回答

0
#Create sample data: 
df <- matrix(rexp(200, rate=.1), ncol=20) 

#Choose the number of columns you'd like to sum up (e.g., 3 or 8) 
number_of_columns_to_sum <- 3 

df2 <- NULL #Set to null so that you can use cbind on the first value below 
for (i in seq(1,ncol(df), by = number_of_columns_to_sum)) { 
    df2 <- cbind(df2, rowSums(df[,i:(i+number_of_columns_to_sum-1)])) 
} 
+0

避免使用'循环(很慢),而且无需使用'这里for'(副作用)内cbi​​nd'。 – agstudy

1

变换你的矩阵到一个数组,然后使用applyrowSums

mat <- structure(c(1L, 1L, 2L, 1L, 2L, 2L, 6L, 2L, 1L, 3L, 3L, 3L, 2L, 4L, 4L, 4L, 5L, 5L, 5L, 10L, 6L, 6L, 6L, 6L), 
       .Dim = c(4L, 6L), 
       .Dimnames = list(c("row1", "row2", "row3", "row4"), c("C.1", "C.2", "C.3", "C.4", "C.5", "C.6"))) 

n <- 3 #this needs to be a factor of the number of columns 
a <- array(mat,dim=c(nrow(mat),n,ncol(mat)/n)) 
apply(a,3,rowSums) 
#  [,1] [,2] 
# [1,] 4 13 
# [2,] 6 15 
# [3,] 11 15 
# [4,] 6 20 
2
# m is your matrix 
n <- 8 
grp <- seq(1, ncol(m), by=n) 
sapply(grp, function(x) rowSums(m[, x:(x+n-1)])) 

如果你是新来R. grp一些解释是一系列数字,让每个组列的出发点:如果你想总结每隔1,9,17,等8列。

sapply调用可以理解如下。对于grp中的每个数字,它将调用rowSums函数,并将与该组号码对应的矩阵列传递给它。因此,当grp为1时,它获得列1-8的行总和;当grp为9时,它获得列9-16的行总和等等。这些是载体,然后sapply然后一起结合成矩阵。

+0

你们真棒!感谢您及时的回复!这正是我需要的! – user2516505

0

另一种选择:虽然它可能不会像优雅

mat <- structure(c(1L, 1L, 2L, 1L, 2L, 2L, 6L, 2L, 1L, 3L, 3L, 3L, 2L, 4L, 4L, 4L, 5L, 5L, 5L, 10L, 6L, 6L, 6L, 6L), 
       .Dim = c(4L, 6L), 
       .Dimnames = list(c("row1", "row1", "row1", "row1"), c("C.1", "C.2", "C.3", "C.4", "C.5", "C.6"))) 

new<- data.frame((mat[,1]+mat[,2]+mat[,3]),(mat[,4]+mat[,5]+mat[,6])) 
names(new)<- c("C.1","C.2") 
new 
+1

相当无用3008 x 3008矩阵,不是吗? – Roland

相关问题