r - r中具有多个条件的switch语句

标签 r switch-statement

我想在 r 中用三个条件编写一个 switch 语句,但似乎无法让它工作。我做错了什么?

# assigning some values
test.type <- "p"
var.equal<- TRUE
  paired <- FALSE

# preparing text for which p-value adjustment method was used
test.description <- switch(
    EXPR = test.type & var.equal & paired,
    "p" & TRUE & TRUE = "Student's t-test",
    "p" & FALSE & TRUE = "Student's t-test",
    "p" & TRUE & FALSE = "Student's t-test",
    "p" & FALSE & FALSE = "Games-Howell test",
    "np" & TRUE & TRUE = "Durbin-Conover test"
  )
#> Error: <text>:10:23: unexpected '='
#> 9:     EXPR = test.type & var.equal & paired,
#> 10:     "p" & TRUE & TRUE =
#>                           ^

reprex package 创建于 2018-11-08 (v0.2.1)

只有一个条件的此语句的更简单版本可以工作-

# simpler switch
(test.description <- switch(
  EXPR = test.type,
  "p"  = "Student's t-test",
  "np" = "Durbin-Conover test"
))
#> [1] "Student's t-test"

reprex package 创建于 2018-11-08 (v0.2.1)

最佳答案

另一种解决方案可能是使用 dplyr 的 case_when,它使用的语法更类似于您的 switch 语句:

library(dplyr)

## initial dataframe
df <- data.frame(
  test.type = c("p", "p", "p", "p", "np", "np"),
  var.equal = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE),
  paired = c(TRUE, TRUE, FALSE, FALSE, TRUE, FALSE)
  ) 

## add column test.description 
mutate(df,
  test.description = case_when(
      test.type == "p" & !var.equal & !paired  ~ "Games-Howell test",
      test.type == "p"                         ~ "Student's t-test",
      test.type == "np" & var.equal & paired   ~ "Durbin-Conover test",
      TRUE                                     ~ "Unknown combination"
     )
)

关于r - r中具有多个条件的switch语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53211392/

相关文章:

php - 如果它们是真实的,如何处理所有情况 PHP

带有输入文本的 Javascript switch 语句

iphone - Obj-C 中奇怪的开关错误

r - 条形图,几何底部和 x 轴之间没有空间,上方保持空间

r - renderDataTable 中的 formatStyle Shiny

r - 通过变量列表为 R 中的 LM 模型创建循环

c - Switch 语句不执行案例 (c)

r - 合并两个 data.frames 并用 df2 的值替换 df1 某些列的值

javascript - Shiny :使用shinyjs禁用tabPanel()

javascript switch() 或 if()