For example:
v1 <- c(10, 11, 20, 30, 40, 50, 30, 25, 20, 10)
In v1
50
is a max number, I need the below result
result <- c(0, 0, 0, 0, 0, (50/40)-1, (30/50)-1, (25/30)-1, (20/25)-1, (10/20)-1)
The final array will look like this
c(0, 0, 0, 0, 0, 0.25, -0.4, -0.16, -0.2, -0.5)
CodePudding user response:
Here is an approach that leverages data.table::shift()
f <- function(v) {
mx = which.max(v);
c(rep(0,mx-1), (v/shift(v)-1)[mx:length(v)])
}
Usage:
f(v1)
Output:
[1] 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.2500000 -0.4000000 -0.1666667 -0.2000000 -0.5000000
CodePudding user response:
in Base R we will do:
idx <- which.max(v1)
index <- seq_along(v1) >= idx - 1
c(numeric(idx - 1), tail(v1[index],-1)/head(v1[index], -1) - 1)
[1] 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.2500000 -0.4000000
[8] -0.1666667 -0.2000000 -0.5000000
CodePudding user response:
We may also do
library(dplyr)
replace((v1/lag(v1))-1, seq_along(v1) < which.max(v1), 0)
-output
[1] 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.2500000 -0.4000000 -0.1666667 -0.2000000 -0.5000000
CodePudding user response:
You can do this in the following, somewhat clunky, way using a combination of base R's which.max()
and dplyr
's lag()
function and some indexing:
c(rep(0,which.max(v1) - 1), v1[which.max(v1):length(v1)] / (dplyr::lag(v1[(which.max(v1)-1):length(v1)]))[-1]-1)
Output:
#[1] 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.2500000 -0.4000000 -0.1666667 -0.2000000
#[10] -0.5000000
To break this down to more palatable code:
numerator <- v1[which.max(v1):length(v1)]
denominator <- lag(v1[(which.max(v1) - 1):length(v1)])[-1]
leading_zeros <- rep(0, which.max(v1) - 1)
c(leading_zeros, numerator/denominator - 1)
#[1] 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.2500000 -0.4000000 -0.1666667 -0.2000000
#[10] -0.5000000