1

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?

Sotos
  • 51,121
  • 6
  • 32
  • 66
Claudio P
  • 165
  • 1
  • 8

1 Answers1

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
  • Can you give some example? – dariober Nov 26 '18 at 11:41
  • 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