user1723765
user1723765

Reputation: 6409

Sum every second value in a vector starting from the third entry

I woud like to apply the following function to a vector instead of a matrix where the vector consists of >100 entries and I would like to add them starting from the third element and adding every second element.

apply(vector,1,function(x) sum(x[seq(3,length(x),2)]))

A quick example would be:

a: 123 4 100 3 594 5 302 ....

What would be added is 100+594+302+...

Upvotes: 1

Views: 2750

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

What about this?

v <- 1:10 # an example vector

sum(v[-1][c(FALSE, TRUE)])
# [1] 24

Upvotes: 3

Related Questions