[R] Funny result from rep(...) procedure

dkStevens david.stevens at usu.edu
Thu Feb 18 19:05:35 CET 2010


I'm observing odd behavior of the rep(...) procedure when using variables as
parameters in a loop. Here's a simple loop on a vector 'branches' that is
c(5,6,5,5,5). The statement in question is           
print(c(ni,rep(i,times=ni)))

that works properly first time through the loop but the second time, when
branches[2] = 6, only prints 5 values of i.

Any ideas, anyone?

  iInd = 1
  for(i in 1:length(branches)) {
    print((1:branches[i])+iInd-1)   # iInd is a position shift of the index
    ni = branches[i]
    print(i)
    print(ni)
    print(c(ni,rep(i,times=ni)))
# ... some interesting other stuff for my project that gets wrecked because
of this issue
    iInd = iInd + branches[i]
}

# first pass through loop
[1] 1 2 3 4 5             # branches[1] + iInd - 1 content
[1] 1                        # i value to repeat 5 times
[1] 5                        # ni = 5 on 1st pass
[1] 5 1 1 1 1 1           # five values - 1 1 1 1 1 - OK

# second pass through loop
[1]  6  7  8  9 10 11   # branches[2] + iInd - 1 content
[1] 2                       # i value to repeat 6 times
[1] 6                       # ni = 6 on 2nd pass
[1] 6 2 2 2 2 2          # 6 'twos' but only shows 5 'twos' 
print(c(ni,rep(i,times=ni))) - why not 6?


-- 
View this message in context: http://n4.nabble.com/Funny-result-from-rep-procedure-tp1560547p1560547.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list