I'd like to write a function that has a vector and a (pos.) number as inputs
and returns what is on the picture below (arithmetic means of (k)
consecutive elements of a given vector). The problem is it works too slow
for long vectors and i know it can be done without "for" loop. However, i've
got no idea how. Can anyone help me with that? 

f1 <- function(v,k) {
  n <- length(v)
  z <- (n-k+1)
  for (i in k:n) {
    v[i-k+1] <- sum(v[(i-k+1):i])
  }
  v <- v[1:(n-k+1)]
  v <- v/k
  return (v) 
}

<http://r.789695.n4.nabble.com/file/n4651030/Untitled.png> 



--
View this message in context: 
http://r.789695.n4.nabble.com/code-optimisation-problem-tp4651030.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to