Love.p
Love.p

Reputation: 3

How can I make a function for calculating variables using two dataframes?

Here are two dataframes, data1 and data2

data1

 id     A     B     C     D    E      F      G
1 id1  1.00  0.31 -3.20  2.50  3.1 -0.300 -0.214
2 id2  0.40 -2.30  0.24 -1.47  3.2  0.152 -0.140
3 id3  1.30 -3.20  2.00 -0.62  2.3  0.460  1.320
4 id4 -0.71  0.98  2.10  1.20 -1.5  0.870 -1.550
5 id5  2.10 -1.57  0.24  1.70 -1.2 -1.300  1.980 

> data2
    factor constant
1      A   -0.321
2      B    1.732
3      C    1.230
4      D    3.200
5      E   -0.980
6      F   -1.400
7      G   -0.300

Actually, data1 is a large set of data with id up to 1000 and factor up to z. data2 also has the factor from a to z and corresponding constant variable.

And, I want to multiply the value of the factor in data1 and the constant of data2 corresponding to the factor, for all factors. And then, I want to create the total of multipliers into a new variable 'total' in data1.

for example> creating 'total' of 'id1'= (A value 1.0 (data1) x A constant -0.32 (data2) + (B value 0.31 x 1.732) + (C -3.20 x 1.230) + ( D 2.5 x 3.2) + (E 3.1 x 0.980) + (F -0.300 x -1.40) + (G -0.214 x -0.300)

Upvotes: 0

Views: 25

Answers (1)

talat
talat

Reputation: 70296

If you have ordered your column names in data1 and the rows in data2 in the same order, you can do:

t(t(dat1[-1]) * dat2$constant)

#         A        B       C      D      E       F       G
#1 -0.32100  0.53692 -3.9360  8.000 -3.038  0.4200  0.0642
#2 -0.12840 -3.98360  0.2952 -4.704 -3.136 -0.2128  0.0420
#3 -0.41730 -5.54240  2.4600 -1.984 -2.254 -0.6440 -0.3960
#4  0.22791  1.69736  2.5830  3.840  1.470 -1.2180  0.4650
#5 -0.67410 -2.71924  0.2952  5.440  1.176  1.8200 -0.5940

Or if you need the totals:

res = t(t(dat1[-1]) * dat2$constant)
res = cbind(res, total = rowSums(res))
res
#         A        B       C      D      E       F       G     total
#1 -0.32100  0.53692 -3.9360  8.000 -3.038  0.4200  0.0642   1.72612
#2 -0.12840 -3.98360  0.2952 -4.704 -3.136 -0.2128  0.0420 -11.82760
#3 -0.41730 -5.54240  2.4600 -1.984 -2.254 -0.6440 -0.3960  -8.77770
#4  0.22791  1.69736  2.5830  3.840  1.470 -1.2180  0.4650   9.06527
#5 -0.67410 -2.71924  0.2952  5.440  1.176  1.8200 -0.5940   4.74386

Upvotes: 1

Related Questions