gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:53:44 27 4
gpt4 key购买 nike

我想在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com