R矩阵求和列向量

R matrix summing columns vector

我有一个向量和一个矩阵如下

vec=c(1,1,1,5,5,7)
mat1=matrix(runif(10*length(vec)),nrow=10)

我想从 mat1 创建一个新矩阵 mat2。

mat2 will have number of columns = distinct elements in vec
1st column of mat2 will be summation of columns of mat1 where vec has value 1 (in this case column 1 to 3)
2nd column of mat2 will be summation of columns of mat1 where vec has value 5 (in this case column 4 to 5)
3rd column of mat2 will be summation of columns of mat1 where vec has value 7 (in this case column 6 to 6)

vec 不会有固定数量的元素,我在上面只提供了一个例子。 vec 将具有升序排列的元素,而 vec 将仅具有整数元素

我想过写一个 for 循环,但我很挣扎,因为 vec 可以有任意数量的元素。

请帮忙。

您可以使用 rowSums 函数对矩阵列的子集求和(在您的情况下,对应于向量中特定值的列)。要迭代向量的所有可能值,您可以使用 sapply:

# Reproducible dataset
set.seed(144)
mat1=matrix(runif(10*length(vec)),nrow=10)

sapply(unique(vec), function(x) rowSums(mat1[,vec == x,drop=F]))
#            [,1]      [,2]        [,3]
#  [1,] 0.8908481 1.1987764 0.200360078
#  [2,] 0.9143586 0.4320678 0.617083644
#  [3,] 1.8743282 0.8998081 0.463207436
#  [4,] 1.2169977 1.9502429 0.116956239
#  [5,] 0.7510266 0.6792186 0.249493016
#  [6,] 1.5971054 0.8156898 0.860322422
#  [7,] 0.7507476 0.7435681 0.976815212
#  [8,] 1.7472541 0.5949144 0.169615928
#  [9,] 1.5338936 0.7695170 0.859721852
# [10,] 1.3822168 1.3014881 0.007783816

drop=F 参数可确保 mat1 的子集仍然是矩阵,即使您 select 是单个列也是如此。

另一个替代方案,具有被忽略的功能,使用 josilber 的 "mat1":

t(rowsum(t(mat1), vec))
#              1         5           7
# [1,] 0.8908481 1.1987764 0.200360078
# [2,] 0.9143586 0.4320678 0.617083644
# [3,] 1.8743282 0.8998081 0.463207436
# [4,] 1.2169977 1.9502429 0.116956239
# [5,] 0.7510266 0.6792186 0.249493016
# [6,] 1.5971054 0.8156898 0.860322422
# [7,] 0.7507476 0.7435681 0.976815212
# [8,] 1.7472541 0.5949144 0.169615928
# [9,] 1.5338936 0.7695170 0.859721852
#[10,] 1.3822168 1.3014881 0.007783816