Notification texts go here Contact Us Buy Now!

How do I use subtraction and addition intermittently on a vector?

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 Formula
2 * 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.

Method 2: Using Vector Indexing 1) First, note that the first two elements are both positive, but after that, they are alternating, so treat 1 separately, extract the even and odd position elements after the first, and sum each, and then subtract the two sums, adding 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

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.