如何在不重复代码的情况下操作多个条件
How to operate multiple conditions without having to repeat the code
我正在尝试创建一个从线性回归中得出结论的函数。函数如下:
- 如果(斜率的)P 值 > 0.05,打印“无线性关联”。
- 如果(斜率的)P 值 <= 0.05,则:
.打印“存在线性关联”
.如果斜率 > 0,打印“这两个变量是正相关的。”
如果斜率 < 0,打印“这两个变量是负相关的。”
.打印“线性回归模型可以解释 {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."
)
}
}
这有帮助吗?
...
sign <- ifelse(B>0, "positively", "negatively")
if(p_value > 0.05) {
glue::glue("No linear association.")
} else {
glue::glue("Exist linear association.
There are {r_squared} amount of Y explainable by the linear regression model.
Y and X are {sign} correlated.")
}
我正在尝试创建一个从线性回归中得出结论的函数。函数如下:
- 如果(斜率的)P 值 > 0.05,打印“无线性关联”。
- 如果(斜率的)P 值 <= 0.05,则:
.打印“存在线性关联”
.如果斜率 > 0,打印“这两个变量是正相关的。”
如果斜率 < 0,打印“这两个变量是负相关的。”
.打印“线性回归模型可以解释 {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."
)
}
}
这有帮助吗?
...
sign <- ifelse(B>0, "positively", "negatively")
if(p_value > 0.05) {
glue::glue("No linear association.")
} else {
glue::glue("Exist linear association.
There are {r_squared} amount of Y explainable by the linear regression model.
Y and X are {sign} correlated.")
}