# 将2个数据帧的不同大小的列相乘 [英] Multiplying columns of different size of 2 data frames

### 问题描述

``````states1 <- c("a", "a", "a", "a", "a", "b", "b", "b", "b", "c", "c", "d", "d", "d")
cities <- c("A","B","C","D","E","F","G","H","I","J","K","L","M","N")
data1 <- c(123, 222, 444, 125, 687, 987, 556, 445, 444, 659, 798, 113, 325, 144)
df1 <- data.frame(states1, cities, data1)
#
states2 <- c("a","a","b","b","c","c","d","d")
classes <- c(1,2,1,2,1,2,1,2)
data2 <- c(65,21,44,25,37,87,58,47)
df2 <- data.frame(states2, classes, data2)
``````

``````multA <- c(123*65, 123*21)
multB <- c(222*65, 222*21)
multK <- c(798*37, 789*87)

df3 <- data.frame(rbind(multA, multB, multK))
colnames(df3) <- c("class 1", "class 2")
``````

### 推荐答案

``````# RESHAPE LONG TO WIDE
rdf2 <- reshape(df2, idvar="states2", v.names="data2", timevar="classes", direction="wide")
# RENAME COLUMNS
rdf2 <- setNames(rdf2, c("states2", "class1", "class2"))

# MERGE AND TRANSFORM
final_df <- transform(merge(df1, rdf2, by.x="states1", by.y="states2"),
class1 = data1 * class1,
class2 = data1 * class2)

final_df

#    states1 cities data1 class1 class2
# 1        a      A   123   7995   2583
# 2        a      B   222  14430   4662
# 3        a      C   444  28860   9324
# 4        a      D   125   8125   2625
# 5        a      E   687  44655  14427
# 6        b      F   987  43428  24675
# 7        b      G   556  24464  13900
# 8        b      H   445  19580  11125
# 9        b      I   444  19536  11100
# 10       c      J   659  24383  57333
# 11       c      K   798  29526  69426
# 12       d      L   113   6554   5311
# 13       d      M   325  18850  15275
# 14       d      N   144   8352   6768
``````