【问题标题】:How to operate multiple conditions without having to repeat the code如何在不重复代码的情况下操作多个条件
【发布时间】:2021-08-21 08:47:53
【问题描述】:

我正在尝试创建一个从线性回归中得出结论的函数。函数如下:

  1. 如果(斜率的)P 值 > 0.05,则打印“无线性关联”。
  2. 如果(斜率的)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


    【解决方案1】:

    这有帮助吗?

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

    【讨论】:

    • 这正是我所需要的。非常感谢!!
    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 2014-10-21
    • 2010-10-18
    • 1970-01-01
    • 2013-04-25
    相关资源
    最近更新 更多