我有一个向量和矩阵如下
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可能有任意数量的元素。
请帮忙。
答案 0 :(得分:3)
您可以使用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
子集保留矩阵。
答案 1 :(得分:2)
使用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