I know this is a stupid question, but is there a function in R that is the opposite of diff, where you can add consecutive pairs in a vector. I.e. if you had the original vector 1, 2, 3, 4, 5, you would get back 3, 5, 7, 11 (1 2, 2 3, 3 4, 4 5)?
CodePudding user response:
You could use filter function.just ensure you have the right felter/kernel for the lag. Ie lag=1
in the diff
function use filter=c(1,1)
in the filter
function. :
x <-1:5
filter(x, c(1,1), sides = 1)
CodePudding user response:
Here are some possibilities:
rowSums(embed(x, 2))
## [1] 3 5 7 9
x |> embed(2) |> rowSums() # same but with pipes
## [1] 3 5 7 9
head(x, -1) tail(x, -1)
## [1] 3 5 7 9
diff(cumsum(c(0, x)), 2)
## [1] 3 5 7 9
c(ts(x) lag(ts(x)))
## [1] 3 5 7 9
library(zoo)
rollsum(x, 2)
## [1] 3 5 7 9
# Since this is a linear operation it has a matrix M
M <- apply(diag(length(x)), 2, rollsum, 2)
c(M %*% x)
## [1] 3 5 7 9
# Take sub or super diagonal of the outer sum
out <- outer(x, x, ` `)
out[row(out) == col(out) - 1]
## [1] 3 5 7 9
Note
x <- 1:5