Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract shifted vectors in R

Tags:

r

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?

like image 659
Noah Watkins Avatar asked Feb 23 '12 22:02

Noah Watkins


People also ask

How do you subtract a vector in R?

To subtract all values in a vector from all values in another vector in R, we can use sapply function with subtraction sign.

How do I subtract a value from a column in R?

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.

Why do we subtract position vectors?

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.


2 Answers

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

like image 81
Henry Avatar answered Sep 26 '22 03:09

Henry


You can use "diff" to get the difference between two consecutive elements in a list,

example :

diff(x)

may help you.

like image 33
Gong-Yi Liao Avatar answered Sep 23 '22 03:09

Gong-Yi Liao