R partial sum of rows/columns of a matrix

风格不统一 提交于 2020-05-29 10:06:04

问题


Is there a way to obtain a KNxN matrix and a NxKN from a KNxKN square matrix?

K: number of industries in the data. N: number of countries in the data.

Each row/colname encodes the 3 code country name e.g. USA, the seperator .c and the number of the industry, e.g. USA.c1 .

I tried to use colSums and rowSums but the functions return only one number instead of N numbers.

Minimal working example for a matrix of 2 industries and 2 countries

           BEL.c30 BEL.c31 CAN.c25 CAN.c26
   BEL.c30   11844      14       1       0
   BEL.c31      85     227       0       0
   CAN.c25       0       0    1037       1
   CAN.c26       0       0      43    1113

The first matrix should like this (row sum across each of the two country ) :

               BEL     CAN
   BEL.c30    11858      1       
   BEL.c31      312     227              
   CAN.c25       0      1038  
   CAN.c26       0      1156

The second matrix should look like this (column sum for each country ) :

              BEL.c30 BEL.c31 CAN.c25 CAN.c26
      BEL    11929      241     1     0
      CAN       0         0     1080  1114

回答1:


Here's one option:

do.call(rbind, tapply(as.data.frame(m), sub("\\.c.*", "", colnames(m)), colSums))
#    BEL.c30 BEL.c31 CAN.c25 CAN.c26
#BEL   11929     241       1       0
#CAN       0       0    1080    1114

do.call(cbind, tapply(as.data.frame(t(m)), sub("\\.c.*", "", colnames(m)), colSums))
#          BEL  CAN
#BEL.c30 11858    1
#BEL.c31   312    0
#CAN.c25     0 1038
#CAN.c26     0 1156


来源:https://stackoverflow.com/questions/37149318/r-partial-sum-of-rows-columns-of-a-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!