Reputation: 26218
This may have been a very basic question, but I am scratching my head ..
Suppose I have a vector v
with 10 elements
v <- 1:10
> v
[1] 1 2 3 4 5 6 7 8 9 10
Now I want to perform some operation (2 argument function) say +
on its elements with previous elements, to get an output like.. 1+1
1+2
2+3
3+4
.. and so on. For the first element where no previous value is there, I'll take first value only. I can perform this operation by manually creating another vector something like c(v[1], v[-length(v)])
, but I think/presume there may be some direct method/in-built function to do so.
> v + c(v[1], v[-length(v)])
[1] 2 3 5 7 9 11 13 15 17 19
#OR if product is the operation
> v * c(v[1], v[-length(v)])
[1] 1 2 6 12 20 30 42 56 72 90
Please guide
Upvotes: 1
Views: 320
Reputation: 72593
Perhaps you may want to try mapply
.
v <- 1:10
init <- v[1]
mapply(`+`, c(init, v[-length(v)]), v)
# [1] 2 3 5 7 9 11 13 15 17 19
mapply(`*`, c(init, v[-length(v)]), v)
# [1] 1 2 6 12 20 30 42 56 72 90
mapply(`^`, c(init, v[-length(v)]), v)
# [1] 1 1 8 81 1024 15625 279936 5764801 134217728 3486784401
Upvotes: 1
Reputation: 388797
This can be achieved with dplyr::lag
or data.table::shift
, although I am not sure if this is what you were looking for.
v + dplyr::lag(v, default = v[1])
#[1] 2 3 5 7 9 11 13 15 17 19
Upvotes: 1