R语言如何正确绘制生成的1000个样本均值的直方图?
修正后的代码实现
方案1:调整for循环逻辑
你之前的for循环仅将均值打印到控制台,没有做持久化存储,且R中for循环本身无返回值,赋值的loop变量为无效空值。调整如下:
set.seed(1234) data <- rexp(1000, rate = 0.2) library(ggplot2) # 初始化向量存储每次生成的样本均值 mean_result <- numeric(1000) for (i in 1:1000) { sample1 <- sample(data, 5) mean_result[i] <- mean(sample1) } # 绘制直方图 ggplot() + geom_histogram(mapping = aes(x = mean_result), binwidth = 0.5, color = "white", fill = "steelblue") + labs(x = "样本均值", y = "频数")
方案2:调整replicate函数用法
你之前设置了simplify = FALSE,会返回列表结构,ggplot无法直接识别列表作为映射数据源。调整如下:
# 省略simplify参数,默认会将结果聚合为数值向量 fivesample1 <- replicate(1000, mean(sample(data, 5))) # 绘制直方图 ggplot() + geom_histogram(mapping = aes(x = fivesample1), binwidth = 0.5, color = "white", fill = "coral") + labs(x = "样本均值", y = "频数")
原代码错误原因
- for循环赋值的
loop变量没有存储任何样本均值,仅打印的内容不会被自动保存到变量中 simplify = FALSE参数让replicate返回列表,ggplot的aes映射仅支持向量类型的输入数据
内容的提问来源于stack exchange,提问作者Scott Hebert
相关产品推荐
相关产品推荐

