[R] For Loop Error

Rui Barradas ruipbarradas at sapo.pt
Sun Jan 29 02:47:43 CET 2012


Hello,

> 
> Every time the loop blows up, I get back this error:
> 
> Error in table.combos[i, ] <- table(combos) :
>   number of items to replace is not a multiple of replacement length
> 

This is because not all colors are present in that one sample that breaks
the code.

> 
> There is no apparent consistency on which "i" in the loop I get this
> error.  
> 
There shouldn't be, every time you run the loop, 'sample' will take
different values. To get
reproducibility you would need 'set.seed'.

A solution could be based on the following.
It's important to sort, like the difference between 'tc1' and 'tc2' proves.
It's 'tc2' you want.

Note that I've reduced the sample size to 10.
Note also that I initialize the matrices to zeros, not NA's.


color <- sort(c('Br','Y','G','R','O','Bl'))

tc1 <- matrix(0, nrow = 1, ncol = 6)
tc2 <- matrix(0, nrow = 1, ncol = 6)

colnames(tc1) <- color
colnames(tc2) <- color

set.seed(123)
for(i in 1) {
  combos <- sample(color, 10, replace = TRUE, prob = P.company)
  tc1[i, unique(combos)] <- table(combos)
  tc2[i, sort(unique(combos))] <- table(combos)
}

table(combos)
tc1
tc2


I hope this helps.

Rui Barradas


--
View this message in context: http://r.789695.n4.nabble.com/For-Loop-Error-tp4336585p4337469.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list