【问题标题】:No Values Returned in Linear Regression Model Function线性回归模型函数中没有返回值
【发布时间】:2021-11-08 21:35:06
【问题描述】:

我正在处理一项任务。我已经做了一次诚实的尝试,所以我想我会伸出手来寻求帮助。

我必须以 10 的样本大小运行引导程序 10 次,并编写一个函数来估计每组输入的线性回归模型。这不是完整的问题,但是,这是我坚持的部分。如果您想了解完整的问题,请告诉我。

这是迄今为止我尝试过的代码。 x 和 y 数据被视为对(x_i, y_i)

rm(list=ls())
x = c(1,1.5,2,3,4,4.5,5,5.5,6,6.5,7,8,9,10,11,12,13,14,15)
y = c(6.3,11.1,20,24,26.1,30,33.8,34.0,38.1,39.9,42,46.1,53.1,52,52.5,48,42.8,27.8,21.9)
n=length(y)

myfunc <- function(data,index){
  # Calculate and return the estimate of linear regression model
  lmout <- lm(data)
  return(lmout$estimate)
}

# call boot
library(boot)

bout = NULL
# Calling boot 10 times...
for(i in 1:10){
  #... with a bootstrap distribution of size 10
  bout = boot(data = y ~ x, statistic = myfunc, R = 10)
}
print(bout$t)

我的问题是当我print(bout$t) 时,它显示一个没有值的列:

 [1,]
 [2,]
 [3,]
 [4,]
 [5,]
 [6,]
 [7,]
 [8,]
 [9,]
[10,]

myfunc (print(lmout)) 中添加打印语句会返回以下输出 100 次:

Coefficients:
(Intercept)            x  
     21.321        1.771  

我假设我生成引导输入的方式出现问题,或者在返回时出现问题。

【问题讨论】:

  • 几个问题。首先,切勿在没有警告的情况下插入rm(list=ls()),因为这可能会删除试图帮助您的人的环境中的对象。其次,您的函数的 index 参数是什么?它永远不会被调用。第三,在循环外运行你的函数,并确保它按照你的想法运行。当我运行 myfunc(data=y ~ x) 时,我得到 NULL。
  • 首先,没有lmout$estimate这样的东西。
  • @dcarlson 我删除了rm(list=ls())。它包含在为该问题提供的数据中。 index 参数包含在问题中,但我不确定何时使用它的上下文。我也得到了 NULL 运行那条线。我从返回语句中删除了$estimate,现在myfunc(data=y ~ x) 返回intercept 21.321x = 1.771,但现在我的启动调用给出了错误Error in t.star[r, ] &lt;- res[[r]] : incorrect number of subscripts on matrix,我不完全确定如何阅读。

标签: r linear-regression bootstrapping


【解决方案1】:

这似乎更像是一个合理的答案:

library(boot)
data <- data.frame(
  x = c(1,1.5,2,3,4,4.5,5,5.5,6,6.5,7,8,9,10,11,12,13,14,15),
  y = c(6.3,11.1,20,24,26.1,30,33.8,34.0,38.1,39.9,42,46.1,53.1,52,52.5,48,42.8,27.8,21.9))

myfunc <- function(data, index){
  # Calculate and return the estimate of linear regression model
  lmout <- lm(y ~ x, data = data[index,])
  coef(lmout)
}
myfunc(data.frame(x,y)) # always run this once to see if you function makes sense

boot(data = data.frame(x,y), statistic = myfunc,
     R = 250)

R = 表示引导应该发生多少次。 index 参数决定了新的“自举”采样。数据必须在 data.frame 中,否则不会放在boot-package 可以抓住它的位置。

【讨论】:

    猜你喜欢
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2018-10-02
    • 2018-04-28
    • 2014-04-17
    • 1970-01-01
    相关资源
    最近更新 更多