简体   繁体   中英

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM