r - How can I perform mathematical operations on array elements referencing i+1 or i-1 indexes? -
i write following code in language. subtractprevious takes array , subtracts i+1st value ith value. how do kind of calculation using r? seems job lapply or maybe dplyr function.
x <- c(1,2,3,4,5,6,7,8,9,10) subtractprevious <- function(x){ (i in 1:length(x)){ if (i == 1) { y[1] <- na } else { y[i] <- x[i] - x[i-1] } } return(y) } y <- subtractprevious(x)
there's built-in function diff this:
c(na,diff(x))
Comments
Post a Comment