# [R] Loop removal possible?

Martyn Plummer plummer at iarc.fr
Mon Aug 21 15:06:38 CEST 2000

```I think this will work:

hilf.w <- function(w){
y <- 0:sum(w)
z <- y*(y+1)/2
indices <- cumsum(c(1,w))
diff(z[indices])
}

Martyn

On 21-Aug-00 Jan Goebel wrote:
> Dear all,
>
> may be somebody have ideas to my following problem:
>
> I have to multiplicate each element of a vector with his position
> in the sorted vector. This isn't a problem ;-)
> But now i have a weighting vector with the weight of each observation,
> and my problem starts. A little example (due to my bad english) maybe
> helps to understand:
>
> x<-c(10,40,50,100)  # income vector for instance
> w<-c(2,1,3,2)       # the weight for each observation in x with the same
> length
>
> simple is without the weighting
> x * (1:length(x))
>
> with weighting the expanded x vector looks like
> "position"    x[i]
> 1             10
> 2             10
> 3             40
> 4             50
> 5             50
> 6             50
> 7             100
> 8             100
>
> To avoid expanding (memory and time consuming) i want to calculate
>
> (1+2)*10
> 3 *40
> (4+5+6)*50
> (7+8)*100
>
> 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)
> }
>
> for the example the function calculate:
>
>> hilf.w(w)
>   3  3 15 15
>
> Thanks a lot in advance for any suggestions,
>
> Jan Goebel (jgoebel at diw.de)
> DIW Berlin
> SOEP
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```