Switch in r

Published onesixx on

switch(statement,item1,item2,item3,…,itemN, default)

# by name with complex named expression
switch("bar", foo={"one"}, bar={"two"})
[1] "two"

# by index
switch(1, "one", "two")
[1] "one"
# by index with complex expressions
switch(2, {"one"}, {"two"})
[1] "two"
# by index with complex named expression
switch(1, foo={"one"}, bar={"two"})
[1] "one"
uFuncSwitch <- function(x){
\tswitch(x,
\t\t"+" = str_c("Addition    : ", num1 + num2) %>% print(),
\t\t"-" = str_c("Subtraction : ", num1 - num2) %>% print(),
\t\tprint("choose another operator")
\t)
}

> num1 <- 6
> num2 <- 4
> uFuncSwitch('+')
[1] "Addition : 10"
> uFuncSwitch('*')
[1] "choose another operator"
https://adv-r.hadley.nz/control-flow.html#switch
x_option <- function(x) {
  switch(x,
    a = "option 1",
    b = "option 2",
    c = "option 3",
    stop("Invalid `x` value")
  )
}
uFuncSwitch <- function(x){
\tswitch(x,
\t\tstr_c("Addition    : ", num1 + num2) %>% print(),
\t\tstr_c("Subtraction : ", num1 - num2) %>% print(),
\t\tprint("choose another operator")
\t)
}

> num1 <- 6
> num2 <- 4
> uFuncSwitch(1)
[1] "Addition    : 10"
> uFuncSwitch(1.6)
[1] "Addition    : 10"
> uFuncSwitch(2.1)
[1] "Subtraction : 2"
> uFuncSwitch(3)
[1] "choose another operator"
https://www.cyclismo.org/tutorial/R/scripting.html#switch-statement
Categories: R Basic

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x