将数据帧的列乘以另一个数据帧中的值

时间:2014-12-12 11:43:22

标签: r

我是R.的新人。所以这可能是一个非常基本的问题要求

我输入数据框为

Id  State   quantity
1   State1  200
2   State2  300
3   State3  500
4   State2  400

Date        State1  State2  State3  
12/3/2014   20.5    200.3   56.3        
12/2/2014   21.5    180.3   60.5    
12/1/2014   19.6    190.0   61.6    
11/30/2014  15.6    195.6   62.6    

输出我试图得到

Date            1           2               3           4
12/3/2014   20.5*200    200.3*300       56.3*500    200.3*400
12/2/2014   21.5*200    180.3*300       60.5*500    180.3*400
12/1/2014   19.6*200    190.0*300       61.6*500    190.0*400
11/30/2014  15.6*200    195.6*300       62.6*500    195.6*400

1 个答案:

答案 0 :(得分:1)

你可以尝试

 dfN <- data.frame(Date=df2$Date)
 dfN[paste0("Id", 1:4)] <- Map(function(x,y) x*y,
       df2[match(df1$State, colnames(df2))], df1$quantity)

 dfN
 #       Date  Id1   Id2   Id3   Id4
 #1  12/3/2014 4100 60090 28150 80120
 #2  12/2/2014 4300 54090 30250 72120
 #3  12/1/2014 3920 57000 30800 76000
 #4 11/30/2014 3120 58680 31300 78240

数据

 df1 <- structure(list(Id = 1:4, State = c("State1", "State2", "State3", 
 "State2"), quantity = c(200L, 300L, 500L, 400L)), .Names = c("Id", 
 "State", "quantity"), class = "data.frame", row.names = c(NA, 
 -4L))

 df2 <- structure(list(Date = c("12/3/2014", "12/2/2014", "12/1/2014", 
 "11/30/2014"), State1 = c(20.5, 21.5, 19.6, 15.6), State2 = c(200.3, 
 180.3, 190, 195.6), State3 = c(56.3, 60.5, 61.6, 62.6)), .Names = c("Date", 
 "State1", "State2", "State3"), class = "data.frame", row.names = c(NA, 
 -4L))