Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R error: "number of items to replace is not a multiple of replacement length"

Tags:

r

matrix

I'm very new to R. My script works fine when value are set lower. I need to calculate probabilities and need at least 1,000,000 samples. My first loop returns this error:

Error in new.matrix[i, ] <- as.vector(table(million.rep[, i])) : number of items to replace is not a multiple of replacement length

My script:

actual.prob <- c(.14, .14, .16, .13, .19, .24)
number.in.bag <- c(8,6,20,9,10,5)

million.rep <- replicate(1000000, sample(1:6, 58, replace= T, actual.prob))



new.matrix <- matrix(nrow= 1000000, ncol=6)
# Note to other readers... the above line throws the error.

for(i in 1:1000000){
new.matrix[i,] <- as.vector(table(million.rep [, i]))
}


y <- c()
for(i in 1:1000000){
y[i] <- sum(new.matrix[i,] == number.in.bag)
}
y
sum(y == 6)
like image 842
user3260832 Avatar asked Oct 20 '22 15:10

user3260832


1 Answers

table counts all occurring elements. If any of 1:6 is missing the output will have a length less than 6, e.g.:

set.seed(1)

## first call; table output is length == 5
table(sample(1:6, size=10, replace=TRUE))
1 2 3 4 6 
1 2 1 3 3 

## second call; table output is length == 4
table(sample(1:6, size=10, replace=TRUE))
2 3 5 6
2 3 4 1

To circumvent this behaviour you could use factors with defined levels (factor(sample, levels=1:6)):

## third call using factors; table output is always length == 6
## please notice the "levels=1:6"
table(factor(sample(1:6, size=10, replace=TRUE), levels=1:6))
1 2 3 4 5 6 
2 2 3 1 0 2 

For your example you could use:

new.matrix[i,] <- as.vector(table(factor(million.rep [, i]), levels=1:6))
like image 183
sgibb Avatar answered Oct 24 '22 00:10

sgibb