数据集中 20 个样本中的 100 个样本,并绘制回归线和人口回归线

100 samples of 20 from the dataset and drawing regression lines along with population regression line

我有一个数据集,其中包含学习时间和成绩两个变量。我想从这个数据集中抽取大约 100 个样本,每个样本 20 个,并显示 100 条回归线和原始回归线。有什么建议吗?

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.6.3
grades = read.csv("https://www.dropbox.com/s/me6wiww943hzddj/grades.csv?dl=1")
qplot(hours, grade, data = grades, geom = "point") + geom_smooth(method = lm)
#> `geom_smooth()` using formula 'y ~ x'

使用循环:

n=100
for(i in 1:n){
  df = grades[sample(1:nrow(grades), 20),]
  g = g + geom_smooth(method = lm, data=df, color="red", size=0.5, alpha = 0)
}
plot(g)

输出:

我鼓励你打乱它的美学,例如添加一条虚线:

我们也可以用sample_n

library(dplyr)
library(ggplot2)
g <- qplot(hours, grade, data = grades, geom = "point") +
      geom_smooth(method = lm)
n <- 100
for(i in seq_len(n)) {
       tmpdat <- grades %>%
                  sample_n(20)
        g <- g +
         geom_smooth(method = lm, data = tmpdat, color = 'red',
                 size = 0.5, alpha = 0)
    }

plot(g)