如何重用r中的调用函数?

时间:2017-08-21 14:30:18

标签: r

逐步选择方法( MASS 库中的 stepAIC )在最后一步提供变量子集。我想通过调用函数来使用它,而不是输入最终模型。我不知道该怎么做!以下是一个例子:

x = as.data.frame(matrix(cbind(rnorm(100), rnorm(100, 10), rnorm(100, 100), rpois(100, 4)), 100, 4))
fit = lm(V1 ~., data=x)
st = stepAIC(fit, direction = "both")
st$call
#  lm(formula = V1 ~ 1, data = x)

如何使用st$call进一步使用?我尝试了下面的内容,希望它会给我回归结果,但它不起作用:

fm = st$call
summary(call)

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用eval()重复使用函数调用。

data(iris)
model <- lm(Sepal.Length~., data = iris)
model
# Call:
#   lm(formula = Sepal.Length ~ ., data = iris)
# 
# Coefficients:
#   (Intercept)        Sepal.Width       Petal.Length        Petal.Width  Speciesversicolor   Speciesvirginica  
# 2.1713             0.4959             0.8292            -0.3152            -0.7236            -1.0235  


eval(model$call)
# Call:
#   lm(formula = Sepal.Length ~ ., data = iris)
# 
# Coefficients:
#   (Intercept)        Sepal.Width       Petal.Length        Petal.Width  Speciesversicolor   Speciesvirginica  
# 2.1713             0.4959             0.8292            -0.3152            -0.7236            -1.0235  

正如您所看到的,两个调用的输出都是相同的。

答案 1 :(得分:0)

返回所选模型。您可以直接使用st。返回的对象附加了更多的信息,因为它是逐步过程的结果,但返回的对象可以而且应该做你想做的所有事情,从而“手动”拟合该模型。

相关问题