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
  • 9,535
  • 1
  • 17
  • 24
0

You can vectorise this with sapply().

out <- sapply(1:length(res), function(x) c - mean(res[1:x]))
Joe
  • 8,073
  • 1
  • 52
  • 58
NRLP
  • 568
  • 3
  • 16