Home > Back-end >  subtraction and division of row values in a data frame column
subtraction and division of row values in a data frame column

Time:10-05

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.

CodePudding user response:

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
  • Related