R: function returns numeric(0) 但代码在函数外工作
R: function returns numeric(0) but code works outside function
我目前正在使用 R,我正在尝试编写一个函数来导出多元线性模型的部分残差。我知道 R 中已有函数,但我想自己编写一个函数。
但是,我的问题是执行函数总是 returns numeric(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
有人知道如何解决这个问题吗?我做错了什么?
感谢您的帮助!
您正在对
中的预测器进行硬编码
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
我目前正在使用 R,我正在尝试编写一个函数来导出多元线性模型的部分残差。我知道 R 中已有函数,但我想自己编写一个函数。
但是,我的问题是执行函数总是 returns numeric(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
有人知道如何解决这个问题吗?我做错了什么?
感谢您的帮助!
您正在对
中的预测器进行硬编码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