Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect an empty quosure in rlang?

Tags:

r

rlang

tidyverse

f <- function(x) enquo(x)

e <- f()
#<quosure: empty>
#~

None of these work:

> is_empty(e)
[1] FALSE
> is_missing(e)
[1] FALSE
> is_false(e)
[1] FALSE
> is_quosure(e)
[1] TRUE
like image 948
Hong Ooi Avatar asked May 25 '17 16:05

Hong Ooi


2 Answers

You can use quo_is_missing(x), which is an alias for is_missing(quo_get_expr(x)).

like image 189
Lionel Henry Avatar answered Nov 16 '22 10:11

Lionel Henry


Examining the print method for class quosure suggests it gets the "empty" attribute like so:

rlang:::env_type(get_env(e))
# [1] "empty"

Unfortunately, env_type is not exported, and neither are the functions env_type calls (ultimately heading to the C function rlang_is_reference)

You can get it more directly (TRUE/FALSE) as:

rlang:::is_reference(get_env(e), empty_env())
# [1] TRUE

Print method for quosure:

rlang:::print.quosure
# function (x, ...) 
# {
#     cat(paste0("<quosure: ", env_type(get_env(x)), ">\n"))
#     print(set_attrs(x, NULL))
#     invisible(x)
# }

I'm not familiar enough with rlang to state with certainty, but this appears to be a way to get what you want using exported functions:

identical(get_env(e), empty_env())
# [1] TRUE

Though I must be missing something, since rlang:::is_reference is not using identical.

like image 30
MichaelChirico Avatar answered Nov 16 '22 09:11

MichaelChirico