Skip to contents

Check that imported packages are actually used

Usage

unused_import_linter(
  allow_ns_usage = FALSE,
  except_packages = c("bit64", "data.table", "tidyverse"),
  interpret_glue = TRUE
)

Arguments

allow_ns_usage

Suppress lints for packages only used via namespace. This is FALSE by default because pkg::fun() doesn't require library(pkg). You can use requireNamespace("pkg") to ensure a package is installed without loading it.

except_packages

Character vector of packages that are ignored. These are usually attached for their side effects.

interpret_glue

If TRUE, interpret glue::glue() calls to avoid false positives caused by local variables which are only used in a glue expression.

See also

linters for a complete list of linters available in lintr.

Examples

# will produce lints
code_lines <- "library(dplyr)\n1 + 1"
writeLines(code_lines)
#> library(dplyr)
#> 1 + 1
lint(
  text = code_lines,
  linters = unused_import_linter()
)
#> ::warning file=<text>,line=1,col=1::file=<text>,line=1,col=1,[unused_import_linter] Package 'dplyr' is attached but never used.

code_lines <- "library(dplyr)\ndplyr::tibble(a = 1)"
writeLines(code_lines)
#> library(dplyr)
#> dplyr::tibble(a = 1)
lint(
  text = code_lines,
  linters = unused_import_linter()
)
#> ::warning file=<text>,line=1,col=1::file=<text>,line=1,col=1,[unused_import_linter] Package 'dplyr' is only used by namespace. Check that it is installed using loadNamespace() instead.

# okay
code_lines <- "library(dplyr)\ntibble(a = 1)"
writeLines(code_lines)
#> library(dplyr)
#> tibble(a = 1)
lint(
  text = code_lines,
  linters = unused_import_linter()
)

code_lines <- "library(dplyr)\ndplyr::tibble(a = 1)"
writeLines(code_lines)
#> library(dplyr)
#> dplyr::tibble(a = 1)
lint(
  text = code_lines,
  linters = unused_import_linter(allow_ns_usage = TRUE)
)