2017-01-16 61 views
0

我遇到了一個小問題,模擬了擲骰子。基本上這樣做是爲了熟悉循環及其輸出。 意向是模擬兩個骰子的擲如下:發生R - 處理隨機子樣本中的零

R = 100 
d6 = c(1:6) 
d = 60 
DICE = NULL 
for (i in 1:R) 
{ 
i <- as.factor((sample(d6, size=d, replace = T)) + (sample(d6, size=d, replace = T))) 
j <- summary(i) 
DICE = rbind(DICE, j) 
} 
head(DICE) 
HIS = colMeans(DICE) 
boxplot(DICE) 
title(main= "Result 2d6", ylab= "Throws", xlab="") 
relHIS = (HIS/sum(HIS))*100 
relHIS 

問題如果結果在一個cathegorie爲0(結果未發生在樣品中)。如果這種情況在第一個子樣本中隨機發生,則會丟失一個或多個類別(數字2-12)。這會在以下子樣本中導致問題(「結果列的數量不是向量長度的倍數(arg 2)」)。 我確定有一個非常簡單的解決方案,通過事先定義一切...

感謝您的幫助!

回答

0

省略as.factor()在第七排

+0

你甚至看過會產生的結果嗎? – Roland

+0

整數,數字介於2和12之間。然後,在做boxplot時,它們應該被認爲是「因素」。 – R18

+0

看看'summary'爲數字輸入產生了什麼。 – Roland

1

這裏有一些修正:

R = 100 
d6 = c(1:6) 
d = 60 
DICE = matrix(nrow = R, ncol = 11) #pre-allocate 
colnames(DICE) <- 2:12 

for (i in 1:R) 
{ 
    sim <- ordered((sample(d6, size=d, replace = T)) + (sample(d6, size=d, replace = T)), 
       levels = 2:12) #define the factor levels 
    sumsim <- table(sim) 
    DICE[i,] <- sumsim #sub-assign 
} 
head(DICE) 
HIS = colMeans(DICE) 
boxplot(DICE) 
title(main= "Result 2d6", ylab= "Throws", xlab="") 

prop.table(HIS) * 100 

總是預先分配的結果的數據結構。在循環中增長非常緩慢,你知道它需要多大。另外,不要對迭代變量和其他東西使用相同的符號。