Home > Blockchain >  How to sum every nth element with its adjacent value in a vector?
How to sum every nth element with its adjacent value in a vector?

Time:11-05

I'm trying to create a vector with 1600 values and I would like to sum adjacent elements. For example, I would like elements 1, 3, 5, 7, 9..., 1599 untouched and elements 2, 4, 6, 8, 10..., 1600 to be the sum of their counterpart value. My code below so far does the trick for the first two elements, where it sums the second value with the first. However, these get repeated for the entire vector the way I have the rep function currently. Is there an easy way to achieve this?

Thanks.

example <- rep(cumsum(rnorm(n = 2, mean = 5000, sd = 1000)), 800)

CodePudding user response:

Let's use simple example vector x <- c(1:10)

To get odd index element, use x[c(TRUE,FALSE)] returns [1] 1 3 5 7 9

To get even index element, x[c(FALSE,TRUE)] returns [1] 2 4 6 8 10

I think I didn't under stand your purpose correctly, but the sum of their counterpart value means add odd index to even index next to it,

x[c(FALSE,TRUE)] <- x[c(FALSE,TRUE)] x[c(TRUE,FALSE)]
x
[1]  1  3  3  7  5 11  7 15  9 19

will do.

  •  Tags:  
  • r
  • Related