[英]how to store 100 values for an exponential distribution
赫敏和羅恩贏得了隨機值的獎品。 Hermione 的獎品是 X 英鎊,Ron 的獎品是 Y 英鎊,其中 X 和 Y 是獨立的指數隨機變量,每個變量的期望值為 1000。編寫 R 命令來模擬 (X,Y) 的一對值並計算 R = X/Y . 創建一個循環來運行上述命令 100 次。 將 X 的 100 個值存儲在向量 Xsample 中,將 Y 的 100 個值存儲在向量 Ysample 中,並將比率 R 存儲在向量 Rsample 中。 在 Xsample、Ysample 和 Rsample 中繪制數據的直方圖。
我知道比率是 0.001。 首先將 x 和 y 是 'rexp(0.001)'。 以及用於存儲 x 的 100 個值的 for 循環將是
for(i in 1:100)
{
i=rexp(0.001)
}
但是,我怎么能用 100 個值來繪制直方圖。我對這個問題想要我做什么很困惑,說實話,你能解釋一下嗎?
這是使用rexp
和 for 循環生成 100 個值的一種方法。 我們可以創建一個空向量並將結果保存到基於索引的向量中。
# Set seed for reproducibility
set.seed(1234)
# Create an empty vector
result <- numeric()
# Use for loop to create values and save the results
for(i in 1:100){
result[[i]] <- rexp(n = 1, rate = 0.001)
}
# See the first six elements in the result
head(result)
# [1] 2501.758605 246.758883 6.581957 1742.746090 387.182584 89.949671
# Plot the histogram
hist(result)
這是生成 100 個值並使用 for 循環的另一種方法。 我們可以使用c
將結果重復組合到向量中。 但是,請注意,此方法比前一種方法慢,因此前一種方法是使用 for 循環保存值的首選方法。
# Set seed for reproducibility
set.seed(1234)
# Create an empty vector
result2 <- numeric()
# Use for loop to create values and save the results
for(i in 1:100){
x <- rexp(n = 1, rate = 0.001)
result2 <- c(result, x)
}
# See the first six elements in the result2
head(result2)
# [1] 2501.758605 246.758883 6.581957 1742.746090 387.182584 89.949671
最后,重要的是要指出rexp
函數有一個參數n
允許我們直接生成 100 個值,而無需使用 for 循環。
# Set seed for reproducibility
set.seed(1234)
# Generate 100 values
result3 <- rexp(n = 100, rate = 0.001)
# See the first six elements in the result3
head(result3)
# [1] 905.2344 932.1655 2296.7747 15.3926 264.8849 933.5238
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.