[R] For Loop Error

Petr Savicky savicky at cs.cas.cz
Sun Jan 29 11:18:39 CET 2012


On Sat, Jan 28, 2012 at 10:25:47AM -0800, Melrose2012 wrote:
> Hi Again,
> 
> I am writing a 'for loop' to create a matrix of randomly sampled colors. 
> I've written this loop in matlab and it works fine.  I then tried to do it
> in R and apparently there is something wrong with my syntax b/c every time I
> run the script, the for loop "blows up" at a different point in the loop.
> 
> As you can see, I ask R to clear my workspace each time, so there shouldn't
> be any variables in my workspace that are messing this up.
> 
> rm(list=ls())
> 
> # Sample Size
> size <- 53  
> # Probability of each color based on company
> P.company <- c(.14,.14,.16,.13,.20,.24)
> # Names of colors
> color <- c('Br','Y','G','R','O','Bl')
> # Make an empty matrix that will be filled in by for loop
> table.combos <- matrix(nrow = 10000, ncol = 6);
> 
> # For loop will run through choosing a random bag of 53 M&Ms 10000 times
> # and create a table enumerating the number of each color in each of these
> 10000 bags
> for(i in 1:10000) {
>   combos <- sample(color,size, replace = TRUE, prob = P.company)
>   table.combos[i, ] <- table(combos)
>   colnames(table.combos)<-c("Br","Y","G","R","O","Bl")
> }
> 
> 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

Hi.

Rui Barradas already pointed out that the problem is with samples,
which do not contain all colors. Forcing table() to produce zero
frequencies of colors, which do not occur, a factor may be used.
Try, for example

  size <- 53
  P.company <- c(.14,.14,.16,.13,.20,.24)
  color <- c('Br','Y','G','R','O','Bl')
  table.combos <- matrix(nrow = 10000, ncol = 6);
  colnames(table.combos) <- color
 
  for(i in 1:10000) {
    combos <- sample(color,size, replace = TRUE, prob = P.company)
    table.combos[i, ] <- table(factor(combos, levels=color))
  }

  which(table.combos==0, arr.ind=TRUE)

         row col
   [1,]  588   1
   [2,] 3005   1
   [3,] 4535   1
   [4,] 8314   1
   [5,] 7654   2
   [6,] 8607   3
   [7,] 1790   4
   [8,] 1980   4
   [9,] 2991   4
  [10,] 4550   4
  [11,] 5868   4
  [12,] 6704   4
  [13,] 8769   4
  [14,] 8823   4
  [15,] 7861   5

Hope this helps.

Petr Savicky.



More information about the R-help mailing list