First argument: numbers vs character
The behaviour of switch(…)
depends on the type of its first argument.
If the first argument's type is a character string, the value of the argument is searched as name in the subsequent arguemnts. The value of the subsequent arguments that matches is returned:
txt <- 'three';
num <- switch(txt,
'one' = 1,
'two' = 2,
'three' = 3,
'four' = 4,
'five' = 5
);
print(paste(txt, '=', num)); # three = 3
In the other cases, the value of the first argument is coerced into an integer. The element that matches tne value of the integer is then returned:
num <- 4;
txt <- switch(num,
'one' ,
'two' ,
'three',
'four' ,
'five'
);
print(paste(num, '=', txt)); # 4 = four
Evaluating expressions
op <- 'times';
val_1 <- 12 ;
val_2 <- 3 ;
switch (op,
plus = { res <- val_1 + val_2; },
times = { res <- val_1 * val_2; },
minus = { res <- val_1 - val_2; },
divided_by = { res <- val_1 / val_2; }
);
cat(paste(val_1, op, val_2, '=', res, "\n"));
#
# 12 times 3 = 36
Switching on a range
In order to test for a range, the
switch
statement can be combined with the
findInterval()
function:
opinion <- 7;
txt <- switch(
findInterval(
opinion, c(
1, 2.5,
4.5,
6.5,
8.5,
10.5)
),
'Strongly disagree',
'Disagree' ,
'Neutral' ,
'Agree' ,
'Strongly agree'
);
print(paste(opinion, 'corresponds to', txt));
#
# 7 corresponds to Agree