R 如何为指数分布存储100个值
赫敏和罗恩赢得了随机值的奖品。赫敏的奖金为X英镑,罗恩的奖金为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)’。对于for循环来说,存储x的100个值也是这样吗R 如何为指数分布存储100个值,r,R,赫敏和罗恩赢得了随机值的奖品。赫敏的奖金为X英镑,罗恩的奖金为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)’。对于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)
最后,需要指出的是,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
#为再现性设定种子
种子集(1234)
#生成100个值
结果3你的两个答案都不正确。仔细查看rexp的帮助页面。在循环中,需要将值存储在向量或列表中,而不是替换迭代参数i
。
# 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