help: Query operator '?'

?R Documentation

Query operator ?

Description

? is a concise interface to query documentation, control flow, type conversion and type check operations.

Usage

? topic

test ? yes ~ no

x ? type

x ?~ type

x ?~ function [...]

Arguments

...

passing optional arguments to further functions.

topic

a topic for which help is sought, usually a name or string.

test

a query, an object which can be coerced to logical mode.

yes

value(s) if query is TRUE.

no

value(s) if query is FALSE.

x

a query, can be a name, logical,

type

an abbreviated class to check for transform x into.

function

a function name specifying the transformation to apply.

Details

ergo::`?` adjusts the 2nd argument of the binary operator ?.

Find documentation:?x

A shortcut to a unary call of base R help. The binary second argument type?topic is dropped. Use utils::`?`(type, topic) to find S4 method documentation. Other than type?pkg (help binary functionality) regular semantics apply.

Execute control flow:test ? yes ~ no   and   x ? type -

This uses if(test) x else y if the query is length 1, and ifelse(test, x, y) otherwise. If yes or no are too short, their elements are recycled.

Type checks and conversion:x ? type   and   x ?~ type

Using the formula interface functions may be applied to the LHS of ?. Void of formula syntax the query is read as is LHS of class RHS?. When a formula is included, it is read as transform the LHS using the template on the RHS. Function arguments can be passed by using [...], names or by position writing square brackets. These brackets are not evaluated.

Value

NULL if documentation, a Boolean if type check.

Operator precedence

? has the lowest operator precedence in R, different from that of infix operators. 1>0 ? 'a'~'b' gives "a", but x = 1>0 ? 'a' ~ 'b' assigns TRUE to x. Thus it is recommended to use parentheses for operations.

For the full list of operator precedence see base::Syntax().

See Also

link[base:ifelse]{base::ifelse} and link[base:Control]{ base::Control} for details on base R control flow.

Examples

x = as.character(1:5)
# is x a character vector?
x ? chr
# if x is character, make it an integer
# old: 'if(is.character(x)) as.integer(x) else x
if(x?chr) (x?~int) else x

## Not run: 
# base R throws an error for if-statement on RHS in pipe
1:4 |> if(sum() > 10) 10 else 5

## End(Not run)
1:4 |> sum() > 10 ? 10 ~ 5

# passing arguments by \code{expr[...]}
e <- list(first = "a", second = FALSE) |> list2env()
as.list(e) ; as.list(e, sorted = TRUE)
e ?~ lst[sorted = TRUE]

# the ? operator can be used in the RHS of a pipe
(1:5 > 3) |> sum() > 3 ? 100 ~ 200

D-Se/ergo documentation built on May 24, 2022, 5:20 p.m.