如何从函数返回对象,而不是调用对象时提供的输出?
best.mod <- function(d){
m1 <- lm(Sepal.Length~Sepal.Width, d)
m2 <- lm(Sepal.Length~Sepal.Width + I(Sepal.Width^2), d)
ifelse(AIC(m1) < AIC(m2), m1, m2)
}
mod <- best.mod(iris[iris$Species == "setosa",])
class(mod)
问题来自使用ifelse
。这是用于矢量化比较。if ... else
这里的标准更好:
best.mod <- function(d){
m1 <- lm(Sepal.Length~Sepal.Width, d)
m2 <- lm(Sepal.Length~Sepal.Width + I(Sepal.Width^2), d)
if(AIC(m1) < AIC(m2)) return(m1) else return(m2)
}
mod <- best.mod(iris[iris$Species == "setosa",])
class(mod)
[1] "lm"
请注意以下警告?ifelse
:
结果的模式可能取决于test的值(请参见示例),并且结果的class属性(请参见oldClass)取自test,并且可能不适用于从yes和no中选择的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句