Home > Mobile >  R function for percentage changes of price
R function for percentage changes of price

Time:10-21

I have a real big problem. I am using RSTUDIO and my task is to find a percentage change of the Average price to the previous day.

Created a new column PercantageCh and I can add value by myself

bitcoin$PercentageCh[3] <- round((bitcoin$AverageP[3]-bitcoin$AverageP[2])/bitcoin$AverageP[2]*100, 3)

How to automize this process for all 2014 rows? Thank you

enter image description here

CodePudding user response:

You can do it with diff:

c(NA, diff(bitcoin$AverageP)) / bitcoin$AverageP
# [1]           NA  0.004805676 -0.011046667  0.005965718
c(NA, diff(bitcoin$AverageP) / bitcoin$AverageP[-nrow(bitcoin)])
# [1]           NA  0.004828882 -0.010925971  0.006001521

(using Matt's bitcoin definition).

Use whichever version depending on whether it is percentage change relative to the previous or the next value. (Notice the parentheses and what is under the /-operator, it is different between the two.)

CodePudding user response:

Try using dplyr::lag,

bitcoin$PercentageCh <- round((bitcoin$AverageP-lag(bitcoin$AverageP))/lag(bitcoin$AverageP)*100, 3)

I was wrong with location of lag

Difference between dlpyr::lag and stats::lag

bitcoin <- data.frame(
  AverageP = rnorm(10)
)
bitcoin$PercentageCh <- round((bitcoin$AverageP-dplyr::lag(bitcoin$AverageP))/dlpyr::lag(bitcoin$AverageP)*100, 3)
bitcoin

     AverageP PercentageCh
1   2.1972088           NA
2   1.4049739      -36.056
3   0.5074163      -63.884
4  -1.4304888     -381.916
5   0.1726630     -112.070
6  -0.9722128     -663.070
7  -0.1076338      -88.929
8   1.1585936    -1176.421
9  -0.2636449     -122.756
10 -1.5825011      500.240

    bitcoin$PercentageCh <- round((bitcoin$AverageP-stats::lag(bitcoin$AverageP))/stats::lag(bitcoin$AverageP)*100, 3)
    bitcoin

     AverageP PercentageCh
1   2.1972088            0
2   1.4049739            0
3   0.5074163            0
4  -1.4304888            0
5   0.1726630            0
6  -0.9722128            0
7  -0.1076338            0
8   1.1585936            0
9  -0.2636449            0
10 -1.5825011            0

CodePudding user response:

With sample data:

bitcoin <- data.frame(AverageP = c(431.8805, 433.9660, 429.2245, 431.8005))

Using a custom function:

pct_change <- function(x){
  round((x - dplyr::lag(x))/dplyr::lag(x)*100,3)
}


bitcoin$PercentageCh <- pct_change(bitcoin$AverageP)

Gives us:

  AverageP PercentageCh
1 431.8805           NA
2 433.9660        0.483
3 429.2245       -1.093
4 431.8005        0.600
  •  Tags:  
  • r
  • Related