[R] Loop removal possible?

ben@zoo.ufl.edu ben at zoo.ufl.edu
Mon Aug 21 15:17:07 CEST 2000


On Mon, 21 Aug 2000, Jan Goebel wrote:

> My solution looks like:
> 
> hilf.w <- function(w) {
>   k <- rep(0,length(w))
>   e <- cumsum(w)       # the end position
>   a <- e-(w-1)         # the beginning position
>   for (i in 1:length(w)) {# <<- this loop i want to remove ??
>     k[i] <- sum(a[i]:e[i])
>   }
>   return(k)
> }
> 

  This seems like a reasonable solution to me -- do you have enormous
problems to do, or do you just want to be elegant?  The dumb answer to
"how do I remove the loop" is

  k <- sapply(1:length(w),function(i)sum(a[i]:e[i]))

(I've sometimes wondered whether it would be worth having an "napply"
command in R where napply(m,n,FUN) was equivalent to sapply(m:n,FUN) [but
executed internally so you didn't have to set aside the vector], but the
efficiency/memory gain would probably be miniscule.)

  Ben


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list