How to Compute the Return of Prices in R (Example Code)
In this article, I’ll explain how to compute the return of a vector of prices in the R programming language.
Introducing Example Data
x <- 1:10 # Example vector in R x # Display example vector in RStudio console # [1] 1 2 3 4 5 6 7 8 9 10 |
x <- 1:10 # Example vector in R x # Display example vector in RStudio console # [1] 1 2 3 4 5 6 7 8 9 10
Example: Calculate Return of Prices Using diff & length Functions
diff(x) / x[- length(x)] # Compute price return # [1] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000 0.1666667 0.1428571 # [8] 0.1250000 0.1111111 |
diff(x) / x[- length(x)] # Compute price return # [1] 1.0000000 0.5000000 0.3333333 0.2500000 0.2000000 0.1666667 0.1428571 # [8] 0.1250000 0.1111111