R – multiplying two data frames

dataframer

In R, i have 2 data frames "df1" and "df2". The df1 and df2 are as follows.

>df1
  date      value
1 1990-10-10  3
2 1990-10-11  2.3
3 1990-10-12  2.5

>df2
  date      value
1 1990-10-10  3
2 1990-10-11  2
3 1990-10-12  2

I need a third data frame "df3", that contains the same column names as df1 and df2. But the value field should be the product of values in df1 and df2.
I am expecting the following output

>df3
  date      value
1 1990-10-10  9
2 1990-10-11  4.6
3 1990-10-12  4

Is it possible in R?

Best Answer

"Merge" the long way with rbind, and use aggregate to produce the products:

aggregate(value ~ date, data=rbind(df1,df2), FUN=prod)
##         date value
## 1 1990-10-10   9.0
## 2 1990-10-11   4.6
## 3 1990-10-12   5.0

If you have mode factor for the value columns of the data frames, you'll have to convert to character then to numeric to extract the value:

df1$value <- as.factor(df1$value)
df2$value <- as.factor(df2$value)

aggregate(as.numeric(as.character(value)) ~ date, data=rbind(df1,df2), FUN=prod)
##         date as.numeric(as.character(value))
## 1 1990-10-10                             9.0
## 2 1990-10-11                             4.6
## 3 1990-10-12                             5.0

You can also convert with as.numeric(levels(value))[value]. See ?factor for details.