【问题标题】:R: function returns numeric(0) but code works outside functionR:函数返回数字(0)但代码在函数之外工作
【发布时间】:2016-09-16 06:53:31
【问题描述】:

我目前正在使用 R 并且我正在尝试编写一个函数来导出多重线性模型的部分残差。我知道 R 中有现有的函数,但我想自己编写一个函数。

但是,我的问题是执行函数总是返回数字(0):

y <- c(2, 3, 6, 8, 12, 15)
x1 <- c(1, 1.5, 2.5, 4, 7, 9)
x2 <- c(10, 22, 30, 31, 38, 42)

fitlm <- lm(y ~ x1+x2)

PR <- function(fit, predictor)
{
PRes <- as.numeric(fit$residuals) + (fit$coefficients["predictor"]*fit$model$predictor)
return(PRes)
}
# with fit = name of linear model and predictor = name of predictor

PR_x1 <- PR(fitlm, x1)
PR_x2 <- PR(fitlm, x2)

但是当我只在函数之外执行代码时,一切正常,我得到了部分残差:

as.numeric(fitlm$residuals)+fitlm$coefficients["x1"]*fitlm$model$x1

有人知道如何解决这个问题吗?我做错了什么?

感谢您的帮助!

【问题讨论】:

标签: r function regression linear-regression


【解决方案1】:

您正在对预测器进行硬编码

fit$coefficients["predictor"]

但我猜你想使用你传入的任何预测器。 这应该可以解决问题:

PR <- function(fit, predictor)
{
  PRes <- fit$residuals + fit$coefficients[predictor] * fit$model[,predictor]
  return(as.numeric(PRes))
}

x <- 1:1000
y <- rnorm(1000)
fit <- lm(y~x)

head(PR(fit,"x"))

打印

> head(PR(fit,"x"))
[1]  0.5813375 -0.2879395  0.1891699  0.8803139  0.9769820  0.5359668

编辑 OP只是提供了一个例子。

如果您想指定预测器本身(即使用变量 x 而不是 "x" 作为字符串)然后

PR2 <- function(fit, predictor)
{
  name <- deparse(substitute(predictor))
  PRes <- fit$residuals + fit$coefficients[name] * fit$model[,name]
  return(as.numeric(PRes))
}

x <- 1:1000
y <- rnorm(1000)
fit <- lm(y~x)

head(PR2(fit,x))

仍然打印

> head(PR2(fit,x))
[1]  1.16292881 -1.03540054  1.86687897 -0.02262028 -1.46575723  1.79580590

【讨论】:

  • 非常感谢!这工作得很好。所以我的错误只是预测器的硬编码?
  • 不,另一个问题是第二部分fit$model$predictor)。由于fit$model 是一个数据框,因此您需要使用fit$model[,predictor] 访问存储在变量predictor 中的列
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 2014-01-17
  • 1970-01-01
相关资源
最近更新 更多