Check that the specified operator is used for assignment.
See also
linters for a complete list of linters available in lintr.
Examples
# will produce lints
lint(
text = "x = mean(x)",
linters = assignment_linter()
)
#> <text>:1:3: style: [assignment_linter] Use <- for assignment, not =.
#> x = mean(x)
#> ^
code_lines <- "1 -> x\n2 ->> y\nz <<- 3"
writeLines(code_lines)
#> 1 -> x
#> 2 ->> y
#> z <<- 3
lint(
text = code_lines,
linters = assignment_linter()
)
#> <text>:1:3: style: [assignment_linter] Use <- for assignment, not ->.
#> 1 -> x
#> ^~
#> <text>:2:3: style: [assignment_linter] Replace ->> by assigning to a specific environment (with assign() or <-) to avoid hard-to-predict behavior.
#> 2 ->> y
#> ^~~
#> <text>:3:3: style: [assignment_linter] Replace <<- by assigning to a specific environment (with assign() or <-) to avoid hard-to-predict behavior.
#> z <<- 3
#> ^~~
lint(
text = "x %<>% as.character()",
linters = assignment_linter()
)
#> <text>:1:3: style: [assignment_linter] Avoid the assignment pipe %<>%; prefer pipes and assignment in separate steps.
#> x %<>% as.character()
#> ^~~~
lint(
text = "x <- 1",
linters = assignment_linter(operator = "=")
)
#> <text>:1:3: style: [assignment_linter] Use = for assignment, not <-.
#> x <- 1
#> ^~
# okay
lint(
text = "x <- mean(x)",
linters = assignment_linter()
)
#> ℹ No lints found.
code_lines <- "x <- 1\ny <- 2\nz <- 3"
writeLines(code_lines)
#> x <- 1
#> y <- 2
#> z <- 3
lint(
text = code_lines,
linters = assignment_linter()
)
#> ℹ No lints found.
# customizing using arguments
code_lines <- "1 -> x\n2 ->> y"
writeLines(code_lines)
#> 1 -> x
#> 2 ->> y
lint(
text = code_lines,
linters = assignment_linter(operator = "->")
)
#> <text>:2:3: style: [assignment_linter] Replace ->> by assigning to a specific environment (with assign() or <-) to avoid hard-to-predict behavior.
#> 2 ->> y
#> ^~~
lint(
text = "x <<- 1",
linters = assignment_linter(operator = "<-")
)
#> <text>:1:3: style: [assignment_linter] Replace <<- by assigning to a specific environment (with assign() or <-) to avoid hard-to-predict behavior.
#> x <<- 1
#> ^~~
writeLines("foo(bar = \n 1)")
#> foo(bar =
#> 1)
lint(
text = "foo(bar = \n 1)",
linters = assignment_linter(allow_trailing = FALSE)
)
#> <text>:1:9: style: [assignment_linter] Assignment = should not be trailing at the end of a line.
#> foo(bar =
#> ^
lint(
text = "x %<>% as.character()",
linters = assignment_linter(operator = "%<>%")
)
#> ℹ No lints found.
lint(
text = "x = 1",
linters = assignment_linter(operator = "=")
)
#> ℹ No lints found.
