math
math

Reputation: 2022

Sum of two elements in a vector

I want to perform the following easy calculation for an example data

a<-seq(1:10)

Now, is there an built-in function,, which returns a vector: (a[1]+a[2],a[3]+a[4],...,a[9]+a[10]). Note I'm able to implement this using a for loop or using rollapply (and deleting some elements). However, I'm wondering if there is a built-in function I do not know so far.

Upvotes: 2

Views: 677

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270348

rollapply in the zoo package can do that in a straightforward manner:

library(zoo)
rollapply(a, 2, by = 2, sum)

Upvotes: 2

pangia
pangia

Reputation: 1164

How about this?

a[c(T,F)] + a[c(F,T)]

Upvotes: 6

Related Questions