R乘以两个数据帧的列

时间:2016-10-28 07:26:32

标签: r dataframe

我有两个数据框,一个是数量,另一个是价格

Quantities <- data.frame(region=c("US","US","EU","China","EU"),a = 1:5, b = 5:9, c=8:12)
prices_frame <- data.frame(region=c("US","EU","China"),a = c(10,20,30), b = c(10,20,30), c=c(1000,2000,100))

  region a b  c
1     US 1 5  8
2     US 2 6  9
3     EU 3 7 10
4  China 4 8 11
5     EU 5 9 12

价格

  region  a  b    c
1     US 10 10 1000
2     EU 20 20 2000
3  China 30 30  100

有没有办法可以快速将数量与匹配区域的价格相乘而无需遍历整个数量框架? 最佳亚历克斯

2 个答案:

答案 0 :(得分:3)

我们可以使用match

假设您的列abc在两个数据帧中的顺序相同

Quantities[-1] * prices_frame[match(Quantities$region, prices_frame$region), -1]


#    a   b     c
#1  10  50  8000
#2  20  60  9000
#3  60 140 20000
#4 120 240  1100
#5 100 180 24000

要获取具有相同列数的数据框,

new_df <- cbind(Quantities[1], 
  Quantities[-1] * prices_frame[match(Quantities$region, prices_frame$region), -1])

#  region   a   b     c
#1     US  10  50  8000
#2     US  20  60  9000
#3     EU  60 140 20000
#4  China 120 240  1100
#5     EU 100 180 24000

答案 1 :(得分:0)

我们可以在data.table

中使用联接
library(data.table)
nm1 <- names(Quantities)[-1]
setDT(Quantities)[prices_frame,  (nm1) := Map(`*`, mget(nm1), 
              mget(paste0("i.", nm1))) , on = "region"]
Quantities
#   region   a   b     c
#1:     US  10  50  8000
#2:     US  20  60  9000
#3:     EU  60 140 20000
#4:  China 120 240  1100
#5:     EU 100 180 24000