简体   繁体   中英

How to test if an object is a formula in base R?

R has many helpers for testing object type, eg is.character(x)

Is there an equivalent for the (strangely missing) is.formula(x) ?

(PS: I see that at least one package has implemented this outside base R)

From my comment, you could just do:

is.formula <- function(x){
   inherits(x,"formula")
}

You could use rlang::is_formula() or rlang::is_bare_formula() from rlang 's doc :

is_formula() tests if x is a call to ~ . is_bare_formula() tests in addition that x does not inherit from anything else than "formula".

inherits() is a common approach but if we want to be rigorous we should look at the call, not the class attribute, as rlang::is_formula() does, I propose a base version here :

a_formula <- ~foo
not_a_formula <- "foo"
class(not_a_formula) <- "formula"

inherits(a_formula, "formula")
#> [1] TRUE
inherits(not_a_formula, "formula")
#> [1] TRUE

is.formula <- function(x) is.call(x) && x[[1]] == quote(`~`)
is.formula(a_formula)
#> [1] TRUE
is.formula(not_a_formula)
#> [1] FALSE

Created on 2019-11-10 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM