Usage like class(x) == "character"
is prone to error since class in R
is in general a vector. The correct version for S3 classes is inherits()
:
inherits(x, "character")
. Often, class k
will have an is.
equivalent,
for example is.character()
or is.data.frame()
.
See also
linters for a complete list of linters available in lintr.
Examples
# will produce lints
lint(
text = 'is_lm <- class(x) == "lm"',
linters = class_equals_linter()
)
#> <text>:1:10: warning: [class_equals_linter] Use inherits(x, 'class-name'), is.<class> or is(x, 'class') instead of comparing class(x) with ==.
#> is_lm <- class(x) == "lm"
#> ^~~~~~~~~~~~~~~~
lint(
text = 'if ("lm" %in% class(x)) is_lm <- TRUE',
linters = class_equals_linter()
)
#> <text>:1:5: warning: [class_equals_linter] Use inherits(x, 'class-name'), is.<class> or is(x, 'class') instead of comparing class(x) with %in%.
#> if ("lm" %in% class(x)) is_lm <- TRUE
#> ^~~~~~~~~~~~~~~~~~
# okay
lint(
text = 'is_lm <- inherits(x, "lm")',
linters = class_equals_linter()
)
#> ℹ No lints found.
lint(
text = 'if (inherits(x, "lm")) is_lm <- TRUE',
linters = class_equals_linter()
)
#> ℹ No lints found.