bln_dev
bln_dev

Reputation: 2411

Apply a function to two elements of a vector

Wow, I'm completely blind... I read the apply, lapply, etc. docs but I wasn't able to find anything.

Let's say I have a vector

a = c(1,4,5,23,6,3,121,412,23)

I want to apply a function to c(1,4), c(4,5), c(5,23), etc. Thus, the resulting vector should be of the length

length(a)-1

I assume, that is really simple. Even, I think I made it already. But thanks for any help.

The function I want to apply is basically the slope or derivative.

Thanks to the answers I have now:

slope = function(p){ 
  return (p[2] - p[1])
}
foo = rollapply(a, 2, slope)

Upvotes: 2

Views: 965

Answers (3)

Dason
Dason

Reputation: 61933

The rollapply function from the zoo package seems to be what you want

> library(zoo)
> a
[1]   1   4   5  23   6   3 121 412  23
> rollapply(a, 2, sum)
[1]   5   9  28  29   9 124 533 435

Note that there are custom rollxxx type functions for specific operations so more detail could provide a more optimized solution.

Edit: After seeing your edit it's clear that all you want is diff.

> diff(a)
[1]    3    1   18  -17   -3  118  291 -389

Upvotes: 7

anon
anon

Reputation:

You could use apply functions, which generally make our life easier. Consider a random function (let's call it foo - I'll only use base-R):

a = c(1,4,5,23,6,3,121,412,23)
new <- as.data.frame(matrix(a, ncol=2, byrow=TRUE))
mapply(foo, new[, 1], new[, 2])

or if vectorized operations are supported by that specific function:

foo(new[, 1], new[, 2])

Upvotes: 0

Colonel Beauvel
Colonel Beauvel

Reputation: 31171

Let's say you want to sum the two elements (1+4 then 4+5, etc). You can use mapply:

mapply(sum, a[-1], head(a,-1))
#[1]   5   9  28  29   9 124 533 435

Upvotes: 3

Related Questions