0

I have two arrays out and res and c a number. I have this code :

for(i in 1:N) {
    out[i] <- c - sum(res[1:i]) / i 
}

Is is possible to simplify this code in a single line, something like this :

out = c - sum(res[1: ???] / i

2 Answers2

1

Do you mean something like c-cumsum(res)/1:length(res)?

user2974951
  • 7,144
  • 1
  • 13
  • 21
0

You can vectorise this with sapply().

out <- sapply(1:length(res), function(x) c - mean(res[1:x]))
Joe
  • 6,965
  • 1
  • 43
  • 53
Luminita
  • 556
  • 3
  • 15