【发布时间】:2021-08-21 08:47:53
【问题描述】:
我正在尝试创建一个从线性回归中得出结论的函数。函数如下:
- 如果(斜率的)P 值 > 0.05,则打印“无线性关联”。
- 如果(斜率的)P 值
. print "存在线性关联"
.如果斜率 > 0,则打印“这两个变量正相关。”
如果斜率 . print "有 {r_squared} 个 Y 可以用线性回归模型解释。"
这是我的代码。虽然它可以工作但看起来不是很优雅,因为我重复了两次代码。 有什么办法可以让这段代码看起来更好看?
conclusion <- function(mydata) {
model <- lm(Y~X, data = mydata)
p_value <- summary(model)$coefficients[2,4]
B <- summary(model)$coefficients[2,1]
r_squared <- summary(model)$r.squared
if(p_value > 0.05) {
glue::glue("No linear association.")
} else if (p_value <= 0.05 && B > 0) {
glue::glue("Exist linear association.
There are {r_squared} amount of Y explainable by the linear regression model.
Y and X are positively correlated."
)
} else {
glue::glue("Exist linear association.
There are {r_squared} amount of Y explainable by the linear regression model.
Y and X are negatively correlated."
)
}
}
【问题讨论】:
标签: r if-statement case nested-if