我的老师给了我一个回归的结果,练习是对导致回归的数据集进行逆向工程.然后我们需要对它做一个回归,找到完全相同的结果.

Regression result

我设法使系数为-19.93,但我没有得到相同的SE.我不知道怎么做.我不知道我是否应该使用一些公式链接的SE估计和标准误差的回归(我有一些,但我真的不知道如何实现他们在R).提前感谢您的帮助!

我的R输出:

## Given values
n <- 1592
se_β1 <- 1.47
β1hat <- -19.93

## Create a dummy variable for control vs treatment condition
set.seed(123)
Low_anchor <- rbinom(n,1,0.5)

## Formula of standard error of beta 1 (assuming homoskedasticity)
calculate_standard_error <- function(u, Low_anchor) {
  sqrt((1/(n - 2))*sum(u^2)/(n*sd(Low_anchor)^2))
}

## Define initial values of u
u <- rnorm(n)

## Tolerance for convergence
tolerance <- 0.1

## Iteratively adjust u until the standard error matches the target
while (abs(calculate_standard_error(u, Low_anchor) - se_β1) > tolerance) {
  ## Generate new set of values for u from a normal distribution
  u <- rnorm(n)
}

print(u)

## regression
Yc <- -19.93*Low_anchor + u
model1 <- lm(Yc ~ Low_anchor - 1)

## Print the summary of the model
summary(model1)

推荐答案

看起来Nc还没有定义. 我认为你在调用独立变量. 我将使用x. 注意,这个问题似乎要求你使用标准误和系数的性质,在(多元)回归的情况下,形式为y = bx + u. 你要知道

  1. 如果你把x乘以某个数字a,估计的系数将是b/a.
  2. 如果你把u乘以某个数字a,估计的标准误差将是a*s.

有了这个,你可以写一个简单的外观,先调整u,然后调整x.首先,我们定义一些基本要素:

n<- 1592
se_b1 <- 1.47
b1hat <- -19.93

set.seed(2)
x <- rnorm(n)
y_mean <- -19.93*x

# we are going to create a random variable to be the residuals
u <- rnorm(n,0,1)

error <- 1
tol <- 0.01

注意,这些分布与答案无关. 你可以判断一下,u的平均值与我们想要的值相差甚远. 您还可以判断运行后会发生什么 y- y_mean + u 摘要(lm(y ~ x)) 系数和标准误差将与您想要的不同.怎么解决?使用我们上面提到的两个属性.

error <- 1
tol <- 0.01

while (error > tol) {
  # remember that the se_b1 is constructed as the rood of the diagonal of sigma^2 * (X'X)^-1
  
  # determine the matrix of X (assuming there is an intercept here)
  X <- matrix(c(rep(1, n), x), ncol = 2)
  XX_minus_one <- solve(t(X) %*% X)
  
  # so far, we would get a standard deviation os
  present_se <- sqrt(var(u) * XX_minus_one[2,2])
  # this is different.  Let's adjust the residuals to have the desired variance
  u_fitting <- u * se_b1 / present_se
  
  y <- y_mean + u
  reg <- lm(y ~ x)
  
  estimated_b1 <- reg$coefficients[2]
  estimated_se_b1 <- summary(reg)$coefficients[2,2]
  
  error <- max(abs(estimated_se_b1 - se_b1), abs(estimated_b1 - b1hat))
  
  # but now we need to refit the x 
  x <- x *  estimated_b1/b1hat
  u <- u_fitting
}

您可以判断它是否工作:

summary(lm(y ~ x))

R相关问答推荐

是否有R代码来判断一个组中的所有值是否与另一个组中的所有值相同?

使用lapply的重新定位功能

有没有一种方法可以从函数中创建一个值的列表,然后将这些值变成R中的直方图?我一直觉得不行

为什么观察不会被无功值变化触发?

整数成随机顺序与约束R?

derrr mutate case_when grepl不能在R中正确返回值

删除列表中存储的数据帧内和数据帧之间的重复行

如何计算多个日期是否在一个日期范围内

从外部文件读取多个值作为字符向量

将一个字符串向量调整为与其他字符串向量完全相同的大小

如何将Which()函数用于管道%>;%

从多个可选列中选取一个值到一个新列中

R中的类别比较

警告消息";没有非缺失的参数到min;,正在返回数据中的inf";.表分组集

如何在反曲线图中更改X标签

在使用SliderInput In Shiny(R)设置输入数据的子集时,保留一些情节痕迹

Ggplot2如何找到存储在对象中的残差和拟合值?

将仪表板中的值框大小更改为Quarto

子样本间系数检验的比较

在直方图中显示两个变量