How to Use Subtraction and Addition Intermittently on a Vector?
To use subtraction and addition intermittently on a vector, you can use the following methods:
Method 1: Using a Custom Formula2 * x[1] + sum(x*(-1)^seq_along(x))
This formula multiplies the first element of the vector (x[1]
) by 2, then adds the remaining elements multiplied by (-1) to the power of their position in the vector. For example, if x = [1, 2, 3, 4, 5]
, this formula will calculate (2 * 1) + (2 * (-1)) + (3 * (-1)^2) + (4 * (-1)^3) + (5 * (-1)^4)
, which equals -1.
x[1]
. Note that this requires that x
have a length of 3 or more.
x <- 1:5
x[1] + sum(x[-1][c(TRUE, FALSE)]) - sum(x[-1][c(FALSE, TRUE)])
## [1] -1
# check
1+2-3+4-5
## [1] -1
2) This can also be written as:
sum(x[1], x[-1][c(TRUE, FALSE)], - x[-1][c(FALSE, TRUE)])
## [1] -1
3) This solution works even if the length of x
is 0, 1, or 2 as well. We create the vector c(1, 1, -1, 1, -1, ...)
and multiply it by x
and sum.
sum(replace(rep(c(-1, 1), length = length(x)), 1, 1) * x)
## [1] -1
Method 3: Using the c()
Function
Here is a way. It will recycle the vector c(1, -1)
to the length of x
. If the length of x
is not even, it gives a warning that must be suppressed since that is expected.
x <- 1:5
sum(c(1, -1) * x) |> suppressWarnings()
#> [1] 3
Edit:
ThomasIsCoding found a bug in the above code. Here is his correction.
x <- 1:5
(x[1] + sum(c(1,-1)*x[-1])) |> suppressWarnings()
#> [1] -1