我试图将两个具有相等列但不等行的数据帧相乘.想法是将数据集B中的每一行与数据集A中的每一行相乘.数据集A.
**Category a1 a2 a3 a4 a5 a6 a7** Food 10 15 28 30 60 33 35 Homecare 14 19 32 34 64 37 39 Apparel 17 22 35 37 67 40 42 Personal 30 35 48 50 80 53 55 AlcBever 33 38 51 53 83 56 58 Footwear 40 45 58 60 90 63 65 NonAlcBev 25 30 43 45 75 48 50
数据集B.
**Country b1 b2 b3 b4 b5 b6 b7** USA 0.5 0.3 0.1 0.4 0.7 0.2 0.8 Sweden 0.6 0.4 0.2 0.5 0.8 0.3 0.9 UK 0.4 0.2 0.1 0.3 0.6 0.1 0.7
我想获得三个结果列(每个国家一个),每行执行以下计算(即sumproduct)
A1*B1 + A2*B2 ........ + A7*B7
我该怎么做?我使用循环吗?
使用矩阵代数:
DF1 <- read.table(text = "Category a1 a2 a3 a4 a5 a6 a7 Food 10 15 28 30 60 33 35 Homecare 14 19 32 34 64 37 39 Apparel 17 22 35 37 67 40 42 Personal 30 35 48 50 80 53 55 AlcBever 33 38 51 53 83 56 58 Footwear 40 45 58 60 90 63 65 NonAlcBev 25 30 43 45 75 48 50", header = TRUE) DF2 <- read.table(text = "Country b1 b2 b3 b4 b5 b6 b7 USA 0.5 0.3 0.1 0.4 0.7 0.2 0.8 Sweden 0.6 0.4 0.2 0.5 0.8 0.3 0.9 UK 0.4 0.2 0.1 0.3 0.6 0.1 0.7", header = TRUE) m1 <- as.matrix(DF1[-1]) rownames(m1) <- DF1[[1]] m2 <- as.matrix(DF2[-1]) rownames(m2) <- DF2[[1]] tcrossprod(m1, m2) # USA Sweden UK #Food 100.9 122.0 82.6 #Homecare 112.9 136.8 92.2 #Apparel 121.9 147.9 99.4 #Personal 160.9 196.0 130.6 #AlcBever 169.9 207.1 137.8 #Footwear 190.9 233.0 154.6 #NonAlcBev 145.9 177.5 118.6