[R] Loop removal possible?

Jan Goebel jgoebel at diw.de
Mon Aug 21 11:59:32 CEST 2000


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)
[1]  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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list