Search code examples
rdplyr

Change the absolute value of elements in a dataframe without changing their sign (+ / -)


I have a dataframe of cumulative changes, which I am trying to convert into (multiplicative) factor values.

If all values were positive, I could simply add 1: e.g. a 25% increase would be 0.25, adding 1 would give me a factor of 1.25, which is correct.

However I have some negative values, these need a subtraction of 1 to be correct e.g. a 25% reduction would be -0.25, subtracting 1 would give me the correct factor or -1.25.

For example with the following dataframe:

  col1  col2
1 0.12 -0.06
2 0.05  0.09

df <- data.frame(col1 = c(0.12, 0.05), col2 = c(-0.06, 0.09))

I would like to get

  col1  col2
1 1.12 -1.06
2 1.05  1.09

Solution

  • You can simply run

    > df + sign(df)
      col1  col2
    1 1.12 -1.06
    2 1.05  1.09
    

    or

    > (1 + abs(df)) * sign(df)
      col1  col2
    1 1.12 -1.06
    2 1.05  1.09
    

    or

    > df + 2 * (df > 0) - 1
      col1  col2
    1 1.12 -1.06
    2 1.05  1.09