问题描述:

I am new to R.
so this might be very basic question to ask

I have input data frames as

Id State quantity

1 State1 200

2 State2 300

3 State3 500

4 State2 400

and

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

Output I am trying to get as

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

网友答案:

You could try

 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

data

 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))
相关阅读:
Top