模拟数据:截距不同但系数相同的两组

Simulating data: Two groups with different intercept but same coefficient

我花了一天的时间试图弄清楚如何模拟我想要的数据——但没有成功。我希望你能帮帮我! 我正在寻找一种方法来复制这个情节:

因此,我正在寻找一种方法来模拟大约 200 个观测值,这些观测值分为两组,系数相同但截距不同。这是怎么做到的?

您可以模拟具有特定均值的正态分布,并将其分布在 x 的某个函数周围。我在这里为

这样做了
  • y = 5 - x + ϕ
  • y = 10 - x + ϕ
  • y = 15 - x + ϕ

其中 ϕ 只是均值为 0 标准差为 1 的标准正态分布的样本:

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.6.3

set.seed(69)

x <- seq(0, 5, length.out = 100)
y1 <- rnorm(100, 5) - x 
y2 <- rnorm(100, 15) - x
y3 <- rnorm(100, 10) - x
groupings <- rep(c("Group1", "Group2", "Group3"), each = 100)
df <- data.frame(x = rep(x, 3), y = c(y1, y2, y3), groupings)

ggplot(df, aes(x, y, colour = groupings)) + 
  geom_point() +
  stat_function(fun = function(x) -x + 5, colour = "red") +
  stat_function(fun = function(x) -x + 10, colour = "blue") +
  stat_function(fun = function(x) -x + 15, colour = "forestgreen")

reprex package (v0.3.0)

于 2020-05-20 创建