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

subtraction and division of row values in a data frame column

The details of the dataframe are

   ID Price Result

    1    20    -0.1
    2    18     0.1667
    3    21    -0.2381
    4    16     0.1875
    5    19    -1

so i have to subtract the second row from first row then divide by the first row. (18-20)/20 = -0.1 but for the last row as there is no next value its like (0-19)/19 = -1
Please help me with this. I am getting NA at the end.

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

>Solution :

transform(df, Result = diff(c(Price, 0))/Price)
  ID Price     Result
1  1    20 -0.1000000
2  2    18  0.1666667
3  3    21 -0.2380952
4  4    16  0.1875000
5  5    19 -1.0000000
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