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

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -