Using lintr

Alexander Rosenstock

This vignette describes how to set up and configure lintr for use with projects or packages.

Running lintr on a project

Checking an R project for lints can be done with three different functions:

For more information about the assumed package structure, see R Packages.

Configuring linters

The .lintr file

The canonical way to configure R projects and packages for linting is to create a .lintr file in the project root. This is a file in debian control format (?read.dcf), each value of which is evaluated as R code by lintr when reading the settings. A minimal .lintr file can be generated by running use_lintr() in the project directory. Lintr supports per-project configuration of the following fields.

.lintr File Example

Below is an example .lintr file that uses 120 character line lengths, disables commented_code_linter, excludes a couple of files.

linters: linters_with_defaults(
    line_length_linter(120), 
    commented_code_linter = NULL
  )
exclusions: list(
    "inst/doc/creating_linters.R" = 1, 
    "inst/example/bad.R", 
    "tests/testthat/exclusions-test"
  )

Other configuration options

More generally, lintr searches for a settings file according to following prioritized list. The first one found, if any, will be used.

  1. If options(lintr.linter_file) is an absolute path, this file will be used. The default for this option is ".lintr".
  2. A linter file (that is a file named like lintr.linter_file) in the currently searched directory, i.e. the directory of the file passed to lint(). When run from lint_package(), this directory can differ for each linted file.
  3. A linter file in a parent directory of the currently-searched directory, starting from the deepest path, moving upwards one level at a time.
  4. A linter file in the user’s HOME directory.

If no linter file is found, only default settings take effect (see defaults).

Using options()

Values in options(), if they are not NULL, take precedence over those in the linter file (e.g. .lintr). Note that the key option_name in the linter file translates to an R option lintr.option_name. For example, options(lintr.exclude = "# skip lint") will take precedence over exclude: # nolint in the linter file.

Using arguments to lint()

The settings can also be passed as arguments to linting functions directly. In case of exclusions, these will be combined with the globally parsed settings. Other settings will be overridden.

If only the specified settings should be changed, and the remaining settings should be taken directly from the defaults, the argument parse_settings = FALSE can be added to the function calls. This will suppress reading of the .lintr configuration. This is particularly useful for tests which should not exclude example files containing lints while the package-level .lintr excludes those files because the lints are intentional.

Defaults

The default settings of lintr are intended to conform to the tidyverse style guide. However, the behavior can be customized using different methods.

Apart from lintr.linter_file, which defaults to ".lintr", there are the following settings:

default
linters lintr::default_linters
encoding UTF-8
exclude regex: #[[:space:]]*nolint
exclude_start regex: #[[:space:]]*nolint start
exclude_end regex: #[[:space:]]*nolint end
exclude_linter regex: ^[[:space:]]*:[[:space:]]*(?<linters>(?:(?:[^,.])+[[:space:]]*,[[:space:]]*)*(?:[^,.])+)\.
exclude_linter_sep regex: [[:space:]]*,[[:space:]]*
exclusions (empty)
cache_directory /Users/jimhester/Library/Caches/org.R-project.R/R/lintr
comment_token (lintr-bot comment token for automatic GitHub comments)
comment_bot TRUE
error_on_lint FALSE

Note that the default encoding setting depends on the file to be linted. If an Encoding is found in a .Rproj file or a DESCRIPTION file, that encoding overrides the default of UTF-8.

Customizing active linters

If you only want to customize some linters, you can use the helper function linters_with_defaults(), which will keep all unnamed linters with the default settings. Disable a linter by passing NULL. For example, to set the line length limit to 120 characters and globally disable the no_tab_linter, you can put this into your .lintr:

linters: linters_with_defaults(
    line_length_linter = line_length_linter(120L),
    no_tab_linter = NULL
  )

By default, the following linters are enabled. Where applicable, the default settings are also shown.

settings
assignment_linter
brace_linter allow_single_line = FALSE
commas_linter
commented_code_linter
cyclocomp_linter complexity_limit = 15L
equals_na_linter
function_left_parentheses_linter
infix_spaces_linter
line_length_linter length = 80L
no_tab_linter
object_length_linter length = 30L
object_name_linter styles = c(“snake_case”, “symbols”)
object_usage_linter
paren_body_linter
pipe_continuation_linter
semicolon_linter allow_compound = FALSE, allow_trailing = FALSE
seq_linter
single_quotes_linter
spaces_inside_linter
spaces_left_parentheses_linter
T_and_F_symbol_linter
trailing_blank_lines_linter
trailing_whitespace_linter
vector_logic_linter

Advanced: programmatic retrieval of linters

For some use cases, it may be useful to specify linters by string instead of by name, i.e. "assignment_linter" instead of writing out assignment_linter().

Beware that in such cases, a simple get() is not enough:

library(lintr)
#> 
#> Attaching package: 'lintr'
#> The following object is masked _by_ '.GlobalEnv':
#> 
#>     default_settings
linter_name <- "assignment_linter"

withr::with_tempfile("tmp", {
  writeLines("a = 1", tmp)

  # linter column is just 'get'
  print(as.data.frame(lint(tmp, linters = get(linter_name)())))

  this_linter <- get(linter_name)()
  attr(this_linter, "name") <- linter_name
  # linter column is 'assignment_linter'
  print(as.data.frame(lint(tmp, linters = this_linter)))

  # more concise alternative: use eval(call(.))
  print(as.data.frame(lint(tmp, linters = eval(call(linter_name)))))
})
#>                                                                               filename
#> 1 /private/var/folders/v4/gklzj0ms5mb3kp20s64y4dcc0000gn/T/RtmpVvJQro/file99766c0e89ee
#>   line_number column_number  type                        message  line linter
#> 1           1             3 style Use <-, not =, for assignment. a = 1    get
#>                                                                               filename
#> 1 /private/var/folders/v4/gklzj0ms5mb3kp20s64y4dcc0000gn/T/RtmpVvJQro/file99766c0e89ee
#>   line_number column_number  type                        message  line
#> 1           1             3 style Use <-, not =, for assignment. a = 1
#>              linter
#> 1 assignment_linter
#>                                                                               filename
#> 1 /private/var/folders/v4/gklzj0ms5mb3kp20s64y4dcc0000gn/T/RtmpVvJQro/file99766c0e89ee
#>   line_number column_number  type                        message  line
#> 1           1             3 style Use <-, not =, for assignment. a = 1
#>              linter
#> 1 assignment_linter

Exclusions

Sometimes, linters should not be globally disabled. Instead, one might want to exclude some code from linting altogether or selectively disable some linters on some part of the code.

Note that the preferred way of excluding lints from source code is to use the narrowest possible scope and specify exactly which linters should not throw a lint on a marked line. This prevents accidental suppression of justified lints that happen to be on the same line as a lint that needs to be suppressed.

Excluding lines of code

Within source files, special comments can be used to exclude single lines of code from linting. All lints produced on the marked line are excluded from the results.

By default, this special comment is # nolint:

file.R

X = 42L # -------------- this comment overflows the default 80 chars line length.

> lint("file.R")

#> <text>:1:1: style: [object_name_linter] Variable and function name style should be snake_case or symbols.
#> X = 42L # -------------- this comment overflows the default 80 chars line length.
#> ^
#> <text>:1:3: style: [assignment_linter] Use <-, not =, for assignment.
#> X = 42L # -------------- this comment overflows the default 80 chars line length.
#>   ^
#> <text>:1:81: style: [line_length_linter] Lines should not be more than 80 characters.
#> X = 42L # -------------- this comment overflows the default 80 chars line length.
#> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^

file2.R

X = 42L # nolint ------ this comment overflows the default 80 chars line length.

> lint("file2.R")

Observe how all lints were suppressed and no output is shown. Sometimes, only a specific linter needs to be excluded. In this case, the name of the linter can be appended to the # nolint comment preceded by a colon and terminated by a dot.

Excluding only some linters

file3.R

X = 42L # nolint: object_name_linter. this comment overflows the default 80 chars line length.

> lint("file3.R")

#> <text>:1:3: style: [assignment_linter] Use <-, not =, for assignment.
#> X = 42L # nolint: object_name_linter. this comment overflows the default 80 chars line length.
#>   ^
#> <text>:1:81: style: [line_length_linter] Lines should not be more than 80 characters.
#> X = 42L # nolint: object_name_linter. this comment overflows the default 80 chars line length.
#> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~

Observe how only the object_name_linter was suppressed. This is preferable to blanket # nolint statements because blanket exclusions may accidentally silence a linter that was not intentionally suppressed.

Multiple linters can be specified by listing them with a comma as a separator:

file4.R

X = 42L # nolint: object_name_linter, line_length_linter. this comment overflows the default 80 chars line length.

> lint("file4.R")

#> <text>:1:3: style: [assignment_linter] Use <-, not =, for assignment.
#> X = 42L # nolint: object_name_linter, line_length_linter. this comment overflows the default 80 chars line length.
#>   ^

You can also specify the linter names by a unique prefix instead of their full name:

file5.R

X = 42L # nolint: object_name, line_len. this comment still overflows the default 80 chars line length.

> lint("file5.R")

#> <text>:1:3: style: [assignment_linter] Use <-, not =, for assignment.
#> X = 42L # nolint: object_name, line_len. this comment still overflows the default 80 chars line length.
#>   ^

Excluding multiple lines of codes

If any or all linters should be disabled for a contiguous block of code, the exclude_start and exclude_end patterns can be used. They default to # nolint start and # nolint end respectively.

# nolint start accepts the same syntax as # nolint to disable specific linters in the following lines until a # nolint end is encountered.

# x <- 42L
# print(x)
#> <text>:1:3: style: [commented_code_linter] Commented code should be removed.
#> # x <- 42L
#>   ^~~~~~~~
#> <text>:2:3: style: [commented_code_linter] Commented code should be removed.
#> # print(x)
#>   ^~~~~~~~
# nolint start: commented_code_linter.
# x <- 42L
# print(x)
# nolint end

(No lints)

Excluding lines via the config file

Individual lines can also be excluded via the config file by setting the key exclude to a list with elements corresponding to different files. To exclude all lints for line 1 of file R/bad.R and line_length_linter for lines 4 to 6 of the same file, one can set

exclude: list(
    "R/bad.R" = list(
      1, # global exclusions are unnamed
      line_length_linter = 4:6
    )
  )

All paths are interpreted relative to the location of the .lintr file.

Excluding files completely

The linter configuration can also be used to exclude a file entirely, or a linter for a file entirely. Use the sentinel line number Inf to mark all lines as excluded within a file. If a file is only given as a character vector, full exclusion is implied.

exclude: list(
    # excluded from all lints:
    "R/excluded1.R",
    "R/excluded2.R" = Inf,
    "R/excluded3.R" = list(Inf),
    # excluded from line_length_linter:
    "R/no-line-length.R" = list(
      line_length_linter = Inf
    )
  )

Excluding directories completely

Entire directories are also recognized when supplied as strings in the exclude key. For example, to exclude the renv folder from linting in a R project using renv, set

exclude: list(
    "renv"
  )

This is particularly useful for projects which include external code in subdirectories.