Let say I have a vector x_n
of size n, and I want to apply a function to every element, except the first, that depends on the previous element f(x_i, x_(i-1)), how can this be done without looping?
Asked
Active
Viewed 131 times
1
-
3Can we have some more info please? – Sotos Nov 26 '18 at 09:58
-
2Note that most of the times "without looping" is just a function that hides a loop inside of it..A reproducible example would help us understand better. – RLave Nov 26 '18 at 10:01
-
if `f` is vectorized, maybe `f(x[-1L], x[-length(x)])`? – chinsoon12 Nov 27 '18 at 01:09
1 Answers
0
What about this? But as noted by @RLave *apply
is just a loop in disguise:
my_fun<- function(i, x) {
if(i == 1){
return(x[i])
} else {
return(x[i] + x[i-1])
}
}
x_n<- c(10, 20, 30, 40 ,50)
sapply(1:length(x_n), my_fun, x_n)
[1] 10 30 50 70 90

dariober
- 8,240
- 3
- 30
- 47
-
So there is no performance advantage in using apply? There is not any sort of precompilation when you use it? – Claudio P Nov 26 '18 at 11:18
-
@ClaudioP No, I don't think there is much advantage. See also https://stackoverflow.com/questions/42393658/lapply-vs-for-loop-performance-r Basically, the main reason for using `*apply` is readability rather than speed. – dariober Nov 26 '18 at 11:32
-
I do get advantage in using sum or prod instead of looping though or it's false even for those? – Claudio P Nov 26 '18 at 11:36
-
-
I guess we are ot, but there is any difference between sum(x) and for( i in 1:length(x)){o=o+x[i]}?, My guess was that sum is an already compiled C function so should be faster. – Claudio P Nov 26 '18 at 11:45