【问题标题】:How to extract the coefficients from a linear model without repeating my code in R?如何从线性模型中提取系数而不在 R 中重复我的代码?
【发布时间】:2021-02-04 21:20:09
【问题描述】:

我正在使用 Montecarlo 模拟来预测 mtcars 数据中的 mpg。我想提取数据框中所有变量的系数,以计算每辆车的 mpg 比另一辆车低多少次。例如,Toyota Corona 的预测 mpg 比 Datsun 710 少多少次。这是我仅使用两个自变量的初始代码。我想扩展此选择以使用数据框中的所有变量,而无需手动包含数据框中的所有变量。 有什么办法可以做到吗?

library(pacman)
pacman::p_load(data.table, fixest, stargazer, dplyr, magrittr)

df <- mtcars
fit <- lm(mpg~cyl + hp, data = df)
fit$coefficients[1]

beta_0 = fit$coefficients[1] # Intercept 
beta_1 = fit$coefficients[2] # Slope
beta_2 = fit$coefficients[3]
set.seed(1)  # Seed
n = 1000     # Sample size
M = 500      # Number of experiments/iterations


estimates_DT <- do.call("rbind",lapply(1:M, function(i) {
  # Generate data
  U_i = rnorm(n, mean = 0, sd = 2) # Error
  X_i_1 = rnorm(n, mean = 5, sd = 5) # First independent variable
  X_i_2 = rnorm(n, mean = 5, sd = 5) #Second ndependent variable
  Y_i = beta_0 + beta_1*X_i_1 + beta_2*X_i_2 + U_i  # Dependent variable
  
  # Formulate data.table
  data_i = data.table(Y = Y_i, X1 = X_i_1, X2 = X_i_2)
  
  # Run regressions
  ols_i <- fixest::feols(data = data_i, Y ~ X1 + X2)  
  ols_i$coefficients
}))

estimates_DT <- setNames(data.table(estimates_DT),c("beta_0","beta_1","beta_2"))

compareCarEstimations <- function(carname1="Mazda RX4",carname2="Datsun 710") {
  car1data <- mtcars[rownames(mtcars) == carname1,c("cyl","hp")]
  car2data <- mtcars[rownames(mtcars) == carname2,c("cyl","hp")]
  
  predsCar1 <- estimates_DT[["beta_0"]] + car1data$cyl*estimates_DT[["beta_1"]]+car1data$hp*estimates_DT[["beta_2"]]
  predsCar2 <- estimates_DT[["beta_0"]] + car2data$cyl*estimates_DT[["beta_1"]]+car2data$hp*estimates_DT[["beta_2"]]
  
  list(
    car1LowerCar2 = sum(predsCar1 < predsCar2),
    car2LowerCar1 = sum(predsCar1 >= predsCar2)
  )
}

compareCarEstimations("Toyota Corona", "Datsun 710")

【问题讨论】:

    标签: r regression montecarlo


    【解决方案1】:

    您的示例我还没有走完,但这里是如何构造一组随机预测变量并将它们与系数向量矩阵相乘以获得预测值的要点:

    设置:

    df <- mtcars
    fit <- lm(mpg~cyl + hp, data = df)
    n <- 1000
    
    beta <- coef(fit) ## parameter vector (includes intercept)
    npar <- length(beta)
    X <- matrix(rnorm(n*npar),ncol=npar)  ## includes intercept
    ## scale columns by the corresponding sd
    ## (all identical in this case)
    X <- sweep(X, MARGIN=2, FUN="*", STATS=rep(5,npar))
    ## shift columns by the corresponding mean
    ## (all identical in this case)
    X <- sweep(X, MARGIN=2, FUN="+", STATS=rep(5,npar))
    Y0 <- X %*% beta
    Y <- rnorm(n, mean=Y0, sd=2)
    

    【讨论】:

    • 感谢您的帮助本。这行代码给我一个错误X &lt;- sweep(X, MARGIN=2, FUN="*", STATS=c(2,rep(5,npar-1))) 这是错误消息Error in array(STATS, dims[perm]) : 'dims' cannot be of length 0 In addition: Warning message: In sweep(X, MARGIN = 2, FUN = "*", STATS = c(2, rep(5, npar - 1))) : STATS is long than the extent of 'dim(x)[MARGIN]'
    • 我正在阅读文档,试图弄清楚你做了什么。只是几个问题。 1) 我之前定义为 u_i 的错误项,现在在 X 里面?基本上为了解决我的问题,我需要将您的方法合并到我的do.call 中,以替代错误术语 X 和 Y?感谢您的帮助!
    • 哎呀,对不起,我把你的 u_i 误读为拦截术语。我要再编辑一点。是的,这就是您生成合成数据的每个副本的地方。
    猜你喜欢
    • 2018-12-03
    • 2021-05-09
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 2019-02-17
    相关资源
    最近更新 更多