How to mirror/reflect a vector relative to the last value

Viewed 81

how can I reflect the vector relative to the last value, I don't know how to explain it in words, so I will show it with pictures enter image description here

enter image description here

I tried to do it myself, but my code only works with linear vector

x <- 1:10 # some linear vector
y <- rev(cumsum(c(tail(x,1),diff(x))))

plot(rep(NA,20),t="l" , ylim = c(1,20))
lines(x,col=2,lwd=5)
lines(y,col=4,lty=5)

enter image description here

If i take an arbitrary vector, my code doesn't work

set.seed(123)
x <- cumsum(rnorm(10))  # real vector
y <- rev(cumsum(c(tail(x,1),diff(x))))

plot(rep(NA,20),t="l" , ylim = c(-5,10))
lines(x,col=2,lwd=5)
lines(y,col=4,lty=5)

enter image description here

1 Answers

I think what you are after is

set.seed(123)
x <- cumsum(rnorm(10))

y <- x-2*(x-tail(x,1))

plot(rep(NA,20),t="l" , ylim = c(-5,10))
lines(x,col=2,lwd=5)
lines(y,col=4,lty=5)

The x-2*(x-tail(x,1)) part adjusts each point with respect to the last point in the line. Basically you find the distance and substract double the distance to move the "opposite side" of that last point. You can move the terms around to simplify a bit to

y <- 2*tail(x,1)-x

enter image description here

Related