ternary_operation: If-Then-Else ternary operator

Description Usage Arguments Value Author(s) Examples

Description

This is a C like ternary operator, the syntax being condition %?% true %:% false.

Usage

1
2
3
condition %?% true

lhs %:% false

Arguments

condition

logical. A vector.

true, false

Values to use for TRUE and FALSE values of condition. They must be either the same length as condition, or length 1.

lhs

Left-hand side of %:%, which should come from the result of a %?% call.

Value

If length(x) > 1, then ifelse is used.

Author(s)

Richie Cotton, see https://stackoverflow.com/a/8791496/3902976; Paul Poncet for the small modifications introduced.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
(capitalize <- sample(c(TRUE, FALSE), 1))
capitalize %?% LETTERS[1:3] %:% letters[1:2]

# Does not work
## Not run: 
capitalize %?% 1*1:3 %:% 1:2

## End(Not run)

# Does work
capitalize %?% {1*1:3} %:% 1:2

# Does work too
capitalize %?% (1*1:3) %:% 1:2

# Vectorized version also works
c(capitalize,!capitalize) %?% "A" %:% c("b","c")

# Chaining operators is permitted 
FALSE %?% "a" %:% 
  (FALSE %?% "b") %:% 
  (capitalize %?% "C") %:% "c" 

bazar documentation built on May 2, 2019, 7:02 a.m.