Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading