Calculating relative difference to the first element in a vector

前端 未结 1 401
情歌与酒
情歌与酒 2021-01-23 09:49

I have a number of vectors of the following form:

vector1 <- c(42.000, 40.781, 40.625, 40.312, 40.375, 40.344, 39.531, 39.875, 40.344, 39.500, 39.125, 39.062,         


        
1条回答
  •  情歌与酒
    2021-01-23 10:12

    It is not clear, what you want to achieve. What do you mean by "starting from 100 as the first value"?

    This gives the difference of all elements to the first element:

    vector1 <- c(42.000, 40.781, 40.625, 40.312)
    vector1-vector1[1]
    #[1]  0.000 -1.219 -1.375 -1.688
    

    This gives the difference to the first element divided by the first element:

    (vector1-vector1[1])/vector1[1]
    #[1]  0.00000000 -0.02902381 -0.03273810 -0.04019048
    

    This gives differences between subsequent elements:

    diff(vector1)
    #[1] -1.219 -0.156 -0.313
    

    0 讨论(0)
提交回复
热议问题