Search code examples
rif-statementcasenested-if

How to operate multiple conditions without having to repeat the code


I'm trying to create a function that pull out conclusion from a Linear Regression. The functions would be like:

  1. If P-value (of the slope) > 0.05, print "No linear association."
  2. If P-value (of the slope) <= 0.05, then:
    . print "Exist linear association"
    . if slope > 0, print "The two variables are POSITIVELY correlated."
    if slope < 0, print "The two variables are NEGAIVELY correlated."
    . print "There are {r_squared} amount of Y explainable by the linear regression model."

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."
    )
  }
}


Solution

  • 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.") 
      }