gpt4 book ai didi

从函数返回一个对象

转载 作者:行者123 更新时间:2023-12-01 23:04:27 25 4
gpt4 key购买 nike

如何从函数返回对象,而不是调用对象时提供的输出?

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 的警告:

The mode of the result may depend on the value of test (see the examples), and the class attribute (see oldClass) of the result is taken from test and may be inappropriate for the values selected from yes and no.

关于从函数返回一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com