2

Edit: Although it works with the suggested solutions when I set all >0 values in df1 to 1 (which I can live with for the moment), I actually do have values >1, so multiplication is not the "perfect" solution for this. I edited the df1 example, now it should be more clear, sorry for the inconvenience.

Searched and did not find any solution to my simple problem, though this is related to many other replace questions. So...

I have two data.frames

df1:

   a   b   c   d
 1 0   0   5   1
 2 0   1   1   0
 3 1   1   3   7

df2:

   value   some_variable
 a  100        234
 b  200        234
 c  300        234
 d  400        234

now I would like to replace values >0 in df1 with the corresponding values in df2$value. So it should look like this:

    a    b    c    d
 1  0    0   300  400
 2  0   200  300   0
 3 100  200  300  400

This is a rather basic question, I guess, but I can't come up with a simple solution. So far I tried ifelse and match but i fail to assign values >0 in df1 columns to the rownames of df2.

Best regards and thanks in advance

eugenego
  • 183
  • 1
  • 1
  • 10

1 Answers1

2

We can do

df1*df2$value[col(df1)]
akrun
  • 874,273
  • 37
  • 540
  • 662