Say I have a vector in R:
x <- c(1,2,3)
is there a concise way to create a new vector y that is one less than the size of x where:
y <- x[i+1] - x[i]
without using a for-loop?
To subtract all values in a vector from all values in another vector in R, we can use sapply function with subtraction sign.
To minus one column from another in an R matrix, we first need to read the matrix as a data frame using as. data. frame then find minus the columns using minus sign and accessing the column of the data frame.
Mastering vector subtraction makes it easier to understand other trigonometry concepts. It gives you a better understanding of the difference between the magnitude and direction of a vector and how two negative values cancel out each other and result in a positive value.
diff(x)
is the obvious answer.
A more basic alternative is x[-1] - x[-length(x)]
and this can easily be adapted for example to sums or products of consecutive terms
You can use "diff" to get the difference between two consecutive elements in a list,
example :
diff(x)
may help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With