1
votes

I need to divide every value in a given column of the first data frame by the value in corresponding column name of the second data frame. For example, I need to divide every value in the 0 column of demand_copy by 25.5, every value in the 1 column by 13.0, etc. and get an output that is the same structure as the first data frame

How would one do this in R?


> head(demand_copy)
   0  1  2  3  4  5  6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23
1 25  9 14  3 10 10 28 175 406 230 155 151 202 167 179 185 275 298 280 185 110  84  93  51
2 36 17  9  3  2  7 32  88 110 131  89 125 149 165 161 147 178 309 339 201 115  78  67  39
3 10  3  5 10  0 11 15  58 129 110  49  62  62 100  70  73  72  86 116  61  49  37  26  22
4 24 15 10  5  3  4 39  53 108  98  80 118 116 110 135 158 157 196 176 132 118  94  91 102
5 40 45 15  9 16 37 75 205 497 527 362 287 316 353 359 309 365 653 598 468 328 242 168 102
6  0  0  1  2  0  0 11  56  26  12  21   6  27  15  18   5  14  19  25   6   4   0   1   0


> medians
   medians
0     25.5
1     13.0
2      8.0
3      4.0
4      4.0
5     10.0
6     38.5
7    106.5
8    205.5
9    164.0
10   111.5
11   130.5
12   160.0
13   164.5
14   170.0
15   183.0
16   202.0
17   282.0
18   256.5
19   178.0
20   109.0
21    80.0
22    60.5
23    41.0

1

1 Answers

4
votes

You could use

t(t(demand_copy) / medians[, 1])

or

sweep(demand_copy, 2, medians[, 1], "/")

Notice that the first approach returns a matrix, whereas the second one returns a data frame.

I also suggest to have medians as a vector, not as a data frame with a single column. Then you could use medians instead of medians[, 1] in the two lines above.