矩阵的行/列的R部分和
有没有办法从K NxK N方阵中获得K NxN矩阵和NxK N?
Is there a way to obtain a KNxN matrix and a NxKN from a KNxKN square matrix?
K:数据中的行业数. N:数据中的国家/地区数.
K: number of industries in the data. N: number of countries in the data.
每个行/名称对3个代码国家/地区名称进行编码,例如美国,分隔符.c和行业编号,例如USA.c1.
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 .
我尝试使用colSums和rowSums,但是函数仅返回一个数字,而不是N个数字.
I tried to use colSums and rowSums but the functions return only one number instead of N numbers.
由2个行业和2个国家组成的矩阵的最小工作示例
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
这里是一个选择:
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