Lukas Lukas - 3 months ago 7
R Question

summing vectors jump one element; alternative for loop in r

I'm sure this is really simple, but I can't get my head around how to vectorise this for loop

x <- 1:3
y <- 11:13

z <- x[1]
for(i in 2:length(x)){
tem <- x[i] + y[i-1]
z <- c(z, tem)
}

Answer

Maybe this?

> c(x[1],tail(x,-1) + head(y,-1))
[1]  1 13 15
Comments