Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reduce vector (A,B,C,D,…) into (A-B,C-D,…)

I want to reduce a vector with length n (where n is even) into length n/2 using R

If the vector was (10,50,30,20,40,70), the output should be (-40,10,-30) i.e. (10-50,30-20,40-70)

I can do this in a loop like so

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

vec <- c(10,50,30,20,40,70)

newVec <- numeric(length(vec)/2)

sequence <- seq(1,length(vec),2)

for (i in 1:(length(vec)/2)) {
  newVec[[i]] <- vec[sequence[i]]-vec[sequence[i]+1]
}
> newVec
[1] -40  10 -30

This is a pretty ugly way to do it though so I was wondering if there was anything better?

>Solution :

diff it:

-diff(matrix(vec, nrow=2))
#     [,1] [,2] [,3]
#[1,]  -40   10  -30
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading