I'm trying to create a function that pull out conclusion from a Linear Regression. The functions would be like:
Here's my code. Although it works but does not look very elegant as I repeated the code twice. Is there any way to make this code looks better?
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."
)
}
}
Does this help?
...
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.")
}