[R] How do I turn NA's to zeroes when a combination lacks one element?

Berend Hasselman bhh at xs4all.nl
Sun Jan 29 18:48:25 CET 2012


On 29-01-2012, at 18:18, C_Crown wrote:

> Hi all, I am  very new to R. I am taking a course and am trying to complete
> my first assignment. 
> For the assignment I have to get the program to generate different color
> combinations possible for a sample size of 55 with the probabilities of each
> color being chosen as: .24, .24, .16, .20, .13, .14. Here is what I've come
> up with... 
> 
> sample.size<- 55
> MM.probability<- c(.24, .24, .16, .20, .13, .14)
> MM.color<- c('Bl','Br','G','O','R','Y')
> mmtable<- matrix(nrow = 1000, ncol = 6)
> for(i in 1:1000){
> combinations<- sample(MM.color, sample.size, replace = T, prob =
> MM.probability)
> mmtable[i,]<-table(combinations)
> colnames(mmtable)<- c("Bl","Br","G","O","R","Y")
> }
> 
> I feel like it should work, but every time I run it, it usually only goes so
> far (maybe to row 350, or 450, sometimes it completes with no problem)
> before I start getting "NA" in every column of every row. I also get this
> error message "Error in mmtable[i, ] <- table(combinations) :  number of
> items to replace is not a multiple of replacement length"
> Someone suggested that it is because the program is coming upon a
> combination that is missing one of the colors, so I'd have to instruct it to
> put a zero in place of the missing color so the simulation can continue,
> which completely makes sense. But I've been trying and can't figure out how
> to do it.

This is homework. "Someone's"  guess as to what is causing the problem is correct.
However:

Create mmtable as a matrix with all 0's and give the columns the names of colors.
Like this

mmtable  <- matrix(0, nrow = 1000, ncol = 6, dimnames=list(c(),MM.color))

Then in the loop replace the lines 

mmtable[i,]<-table(combinations)
colnames(mmtable)<- c("Bl","Br","G","O","R","Y")

with

    z <- table(combinations)
    mmtable[i,names(z)] <- z

The second line stores the entries in z in the columns with the same column name and leaves the others alone.

Since you initialized mmtable with 0's you won't need to replace NA's with 0.

Berend



More information about the R-help mailing list