Function calculating 9 sums (of 'consecutive elements') of a vector with 10 elements

by Fabio   Last Updated July 12, 2019 14:26 PM - source

let's say I have a vector

 test1 <- 1:10 

I want to write a function that sums the values of 2 consecutive elements of this vector. The output will therefore necesseraly be of length 'test1 -1'.

I looked up on the internet and found most of the times suggestions with loops. I am very new to R and still don't really get the syntax of loops and furthermore, I'd like to have a function because what I really want to do at the end is apply this function using the purrr package to a larger dataset. So I am really just looking for the code of this simple function so that I can use it afterwards for my big dataset. Also, I red something about "rolling window functions", which seems to be promising, but again, I am very new to R and I would like to keep it simple. The "cumsum" function is not what I am looking for as I am interested in the sum between 2 consecutive elements instead of the cumulative sum over all elements.

The biggest problem I have right now is that I don't know how to tell R that really what I'm trying to sum over are consecutive positions rather than 2 values (not quite sure if you get what I mean). I tried stuff like

sum_fun1 <- function(x) {
  [x] + [x+1]

but he doesn't get that x in that case refers to a position really, rather than the content of that position / element.

Thanks a lot <3

Tags : r sum

Answers 1

You can use the rollapply function from the zoo package:

test1 <- 1:10
x <- rollapply(test1, 2, sum)

In this case the first argument is your data, the second is the width of the rolling window (number of observations) that you are considering; in your case, this is 2 since you are dealing with consecutive sums. The third argument is the function you want to apply to each rolling window, in this case, sum. You should be able to use it in your function.

July 12, 2019 14:16 PM

Related Questions