case | R Documentation |
Avoids nested ifelse statements when the action depends on the value of a variable
case(.select., ...)
.select. |
a variable whose values determine the argument to be used |
... |
named arguments and one possibly unnamed argument. |
Each argument in ... evaluates
to a vector whose value is returned where the name of the
argument matches a value of .select.
.
The vectors in ... are combined into a matrix with
cbind
and the names of the arguments
are used as values of .select.
to select which
vector value is returned. See the examples.
If there is an unnamed argument, its value is used
as a value in .select.
is not matched by
an argument name.
See an alternative: case_when
x <- c(letters[1:4],NA)
case(x, a = 'was an a', b = 'was a b', z = 'was a z')
case(x, a = 'was an a', x) # x is returned as default
# numerical 'select' is coerced to character
case(1:4, '1' = 'was a 1', '2' = 'was a 2')
location <- c('England','England','France','France',
'Germany','Spain')
xvar <- c('yes','no','non','oui','nein','si')
case(location,
'England' = tr(xvar, c('yes','no'), c(1,0)),
'France' = tr(xvar, c('oui','non'), c(1,0)),
'Germany' = tr(xvar, c('nein','ja'), c(0,1)))
case(location,
'England' = tr(xvar, c('yes','no'), c(1,0)),
'France' = tr(xvar, c('oui','non'), c(1,0)),
'Germany' = tr(xvar, c('nein','ja'), c(0,1)),
xvar)
case(location,
'England' = tr(xvar, c('yes','no'), c(1,0)),
'France' = tr(xvar, c('oui','non'), c(1,0)),
'Germany' = tr(xvar, c('nein','ja'), c(0,1)),
'no match')
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.