Skip to content

lms: lint variable labels hardcoded in plot and table code - #190

Merged
d-morrison merged 3 commits into
mainfrom
claude/project-thread-9efbnj
Nov 20, 2026
Merged

d-morrison merged 3 commits into
mainfrom
claude/project-thread-9efbnj

Conversation

@d-morrison

@d-morrison d-morrison commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Requested by Ezra · project thread

Closes #189.

Why

Ezra (2026-11-19): "lint R code to enforce that labels are applied to data as attributes during preprocessing, not on the fly while constructing graphs, tables, etc", pointing at the lds splines lab's EDA, where labs(x = "Wage (thousands of dollars)", y = "Number of workers") names the axes in the plotting code.
ggplot2 4.0 titles each axis and legend from the mapped column's label attribute (checked with ggplot2 4.0.4: get_labs() returns the attribute), so data labelled once in preprocessing needs no labs() call.

What

  • lms/R/hardcoded_label_linter.R: new hardcoded_label_linter(), an XPath linter that flags a hardcoded label given as a variable's label in:

    • labs(), except title, subtitle, caption, tag, alt and alt_insight (they describe the plot, not a variable); an inline dictionary is flagged, a named vector made in preprocessing is not;
    • xlab(), ylab(), a scale_*() name (named, or the first positional argument wherever it sits; not for scale_discrete_manual() and the identity scales, whose first argument is the aesthetics), and a guide_*() title (named or first positional);
    • an xlab, ylab or zlab argument of any call except c(), list(), set_variable_labels() and var_label(), such as base graphics' plot() and hist() (lds has about 90);
    • kable(col.names =), datatable(colnames =), gt::cols_label() and flextable::set_header_labels().

    A value is hardcoded when it is a string literal; a c() or list() with one among its values; or a paste(), paste0(), sprintf(), glue(), md() or html() with one among its unnamed arguments (named options such as sep and collapse are not label text). These builders nest up to three calls deep.
    A label read from the data (labelled::var_label(df[["x"]])), expression() and NULL pass.

  • lms/R/default_linters.R, lms/NAMESPACE, lms/man/*.Rd (roxygen2 output): the linter joins the nested_calls = TRUE group, beside ggplot_args_linter().

  • lms/tests/testthat/test-hardcoded_label_linter.R: positive and negative cases for each function family, the plot-description exemptions, base graphics, the dictionary case, each case from the agy review below, and membership in default_linters().

  • lms/README.md: lists the sixth linter.

  • chapters/coding-practices/documenting-code.qmd: new "Read labels from the data in plots and tables" subsection under Variable labels, with the preprocessing pattern, a counter-example, labs(dictionary =) for a computed variable such as a histogram's count, and kable(col.names =) from labelled::var_label(..., null_action = "fill").

Review follow-up

12e7345 fixes the five XPath gaps in the agy review of 9eebdac: named sep/collapse/.sep options, builders nested in c()/list(), scale_discrete_manual(), xlab keys in label containers, and a first positional argument after a comment or a named argument, plus md()/html().

Rollout

On the current lds subfiles the first version of the linter reported 605 lints in 290 files, so there is no sweep:
each repository's lint-changed-lines workflow lints only added or edited lines, and the rule takes effect there once its lms-ref moves to this PR's merge commit.
The splines lab example gets its own small lds PR after that bump.

Checks run

  • testthat::test_local("lms"): 192 pass, 0 fail.
  • lintr::lint() with the repo's .lintr.R on the changed R files: no lints.
  • typos on the changed files: clean.
  • quarto render chapters/coding-practices.qmd --to html: renders; read the new subsection in the output.

Annotations

The annotation gate reported 2 annotations on 9eebdac, both notices, and both unrelated to this diff:

  • build / build: "SUBMODULES_TOKEN is empty; cloning submodules anonymously". The macros submodule is public, so the anonymous clone works.
  • review / claude-review: "Skipping element-level diff highlighting: 798 old / 808 new candidate elements exceed the 500-element cap". This is a limit of the review's render diff, not a defect.

Note: under a C locale, lintr's xml_nodes_to_lints() errors on a flagged string with a non-ASCII character (such as "Log-odds η"), because columns are counted in bytes; under a UTF-8 locale, as on CI, it works.

🤖 Generated with Claude Code

https://claude.ai/code/session_019xfc9nB5JcJvBYV4BRx5Dq

Ezra asked for a lint rule that keeps variable labels on the data,
set once in preprocessing, rather than typed into labs(), xlab(),
ylab() or a table's column names each time a plot or table is built.
ggplot2 4.0 titles axes and legends from a column's label attribute,
so labelled data needs no labs() call.

Add lms::hardcoded_label_linter(), part of
default_linters(nested_calls = TRUE), which flags a string literal
(or c()/list()/paste0() of one) given as a variable's label in labs()
(not title, subtitle, caption, tag or alt), xlab(), ylab(), a scale's
name, a guide's title, kable(col.names =), DT::datatable(colnames =),
gt::cols_label() and flextable::set_header_labels().
Document the pattern, including labs(dictionary =) for computed
variables such as a histogram's count, in the Variable labels section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019xfc9nB5JcJvBYV4BRx5Dq
@d-morrison d-morrison self-assigned this Nov 20, 2026
plot(x, y, xlab = "...") and hist(x, xlab = "...") hardcode a label
the same way labs() does; lds has about 90 such arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019xfc9nB5JcJvBYV4BRx5Dq
@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@d-morrison

Copy link
Copy Markdown
Contributor Author

Cross-model review (agy, gemini-4-hydrogen-high) of head 9eebdac:

Summary

PR #190 adds hardcoded_label_linter() to lms (exported, documented, tested, and wired into default_linters(nested_calls = TRUE) and lms/README.md) along with a new #sec-labels-from-data subsection in chapters/coding-practices/documenting-code.qmd. The documentation examples, NAMESPACE, .Rd files, and test cases match the PR description, but hardcoded_label_xpath() in lms/R/hardcoded_label_linter.R has several XPath false positives and false negatives around paste()/paste0()/glue() named options, nested builder calls, scale_discrete_manual(), unscoped xlab/ylab/zlab, and leading comments.

Findings

  1. False positive on sep / collapse / glue() control arguments (lms/R/hardcoded_label_linter.R, hardcoded_label_xpath()):
    is_literal checks expr[position() > 1][STR_CONST] on any c(), list(), paste(), paste0(), sprintf(), or glue() call without excluding named formatting/control arguments. Calls that format labels read from data or variables—such as paste(x_label, y_label, sep = ""), paste0(label_parts, collapse = ", "), or glue::glue("{x_label}", .sep = ", ")—have a STR_CONST expression at position() > 1 for sep, collapse, .sep, .open, .close, .na, or .comment, and are falsely flagged even though no label text is hardcoded. Excluding named option arguments (or only checking unnamed arguments for paste/paste0/glue) avoids this.

  2. False negative on nested builders inside c() or list() (lms/R/hardcoded_label_linter.R, hardcoded_label_xpath()):
    is_literal checks expr[position() > 1][STR_CONST] only one level deep. When a dynamic string builder is nested inside c() or list()—for example labs(dictionary = c(count = paste0("Number of ", item))), flextable::set_header_labels(ft, values = list(age = paste0("Age (", unit, ")"))), or knitr::kable(df, col.names = c(paste0("Age (", unit, ")"), labelled::var_label(df$wage)))—the inner paste0() argument <expr> has no direct STR_CONST child, so the linter misses it. (Note that switching directly to .//STR_CONST would falsely flag c(labelled::var_label(df[["age"]]), ...) because "age" is a descendant STR_CONST, so recursion should follow builder calls specifically.)

  3. False positive on ggplot2::scale_discrete_manual() (lms/R/hardcoded_label_linter.R, hardcoded_label_xpath()):
    scale_call matches every starts-with(text(), 'scale_') call and first_arg flags an unnamed first argument if it is a string literal or c(). Unlike scale_x_continuous() and other scale_*() functions whose first parameter is name (or passes through ... to name), ggplot2::scale_discrete_manual(aesthetics, ..., values) takes aesthetics as its first positional parameter. Calling scale_discrete_manual("colour", values = cols) or scale_discrete_manual(c("colour", "fill"), values = cols) will be falsely flagged.

  4. False positive from unscoped xlab / ylab / zlab (lms/R/hardcoded_label_linter.R, hardcoded_label_xpath()):
    paste0("/", named_arg(any_text(c("xlab", "ylab", "zlab")))) expands to //SYMBOL_SUB[text() = 'xlab' or text() = 'ylab' or text() = 'zlab']/following-sibling::expr[1], matching any call in a file. Although intentionally broad per the PR description, it also flags preprocessing code if a column or helper key happens to be named xlab, ylab, or zlab (for example, labelled::set_variable_labels(df, xlab = "...") or plot_labels <- list(xlab = "...")).

  5. False negative on scale_*() / guide_*() with a leading comment or preceding named argument, and gt::cols_label() with md() / html() (lms/R/hardcoded_label_linter.R):

    • first_arg uses preceding-sibling::*[1][self::OP-LEFT-PAREN], which fails if a # comment sits between ( and the first positional argument (preceding-sibling::*[1] is COMMENT), or if a named argument precedes a positional name/title (e.g., scale_x_continuous(limits = c(0, 10), "Age")).
    • gt::cols_label(age = md("**Age**")) and gt::cols_label(age = html("Age")) are common ways to hardcode labels in gt tables, but md and html are not in builders.

Verdict

The documentation, tests, namespace exports, and PR summary align well, but the XPath expression in hardcoded_label_linter.R contains genuine false positives (sep/collapse in paste/paste0/glue, scale_discrete_manual(), unscoped xlab/ylab/zlab) and false negatives (nested paste0/sprintf/glue inside c()/list(), comments before first_arg).

VERDICT: NOT CLEAN

Reviewed-Commit: 9eebdac

Posted by Claude Code (AI agent) --- not written by a human.

The agy review of 9eebdac found five XPath gaps:
- named options of paste()/paste0()/glue() (sep, collapse, .sep) were
  read as label text; only unnamed arguments of formatting calls count;
- a formatting call nested in c() or list() was missed; builders now
  nest up to three levels;
- scale_discrete_manual() and the identity scales take the aesthetics
  first, so their first argument is no longer read as a name;
- xlab/ylab/zlab keys inside c(), list(), set_variable_labels() and
  var_label() were flagged; those name labels, not axis titles;
- the first positional argument was missed after a comment or a named
  argument, and gt's md() and html() were not checked.
Each case has a test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019xfc9nB5JcJvBYV4BRx5Dq
@github-actions

Copy link
Copy Markdown
Contributor

Claude finished review — View run


I fetched PR #190 live just now. It is open, not a draft, and not merged, and its head is still 12e7345962e18a6db549a8cfc3af5348bcda4945, the commit I reviewed. The review above applies to that head, and the verdict stands.

Two things from this turn:

  • gh field error: my first fetch failed because gh pr view --json has no merged field. The field that works is mergedAt, which is null here. I haven't recorded this anywhere, so the next session may hit the same error.
  • apt install: I installed R and its dependencies via apt only to run the tests. That is a one-off for this review, so I'm not suggesting a change to the cloud startup script.

Verdict

Ready for merge

Structured Review Data (JSON)
{
  "schema_version": "1.1",
  "reviewer": "claude",
  "commit_sha": "12e7345962e18a6db549a8cfc3af5348bcda4945",
  "verdict": "CLEAN",
  "findings": [],
  "detailed_assessment": "Ran lms/tests/testthat/test-hardcoded_label_linter.R at 12e7345: 45 passed, 0 failed, with warnings only from the missing cyclocomp package; the new unnamed-argument, nesting, md/html and label-container XPath logic behaves as documented.",
  "holistic_assessment": "The commit narrows false positives and negatives in the opt-in linter without adding dependencies or changing scope; docs, Rd and tests agree, so the prior Ready for merge verdict still stands."
}

Reviewed commit: 12e7345

@github-actions

Copy link
Copy Markdown
Contributor

💰 Cost: $0.2642 (review) — run

@github-actions

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.2
🚀 Preview available at: https://Morrison-Lab.github.io/psc/pr-preview/pr-190/

Built to branch gh-pages at 2026-11-20 07:57 UTC.

@d-morrison

Copy link
Copy Markdown
Contributor Author

Cross-model review (agy, gemini-4-hydrogen-high) of head 12e7345:

Summary

Commit 12e7345962e18a6db549a8cfc3af5348bcda4945 resolves all five findings from the earlier review of 9eebdac02f6d8a2cec8e14ed5d5e1129e11ee778:

  1. Named formatting options (sep, collapse, .sep, etc.): literal_label_test() in lms/R/hardcoded_label_linter.R now distinguishes collectors (c(), list()) from formatters (paste(), paste0(), sprintf(), glue(), md(), html()) and filters formatter arguments with is_unnamed (not(preceding-sibling::*[not(self::COMMENT)][1][self::EQ_SUB])), so named options like sep = "" and .sep = ", " are ignored.
  2. Nested builders inside c() or list(): literal_label_test(depth = 3L) nests collector and formatter checks up to three levels deep while still ignoring non-builder expressions such as labelled::var_label(df[["age"]]).
  3. scale_discrete_manual() and identity scales: named_first_scale excludes scale_discrete_manual, scale_discrete_identity, and scale_continuous_identity from first_positional, while keeping the named name = check on all scale_*() calls.
  4. Unscoped xlab / ylab / zlab: axis_arg_call excludes c(), list(), set_variable_labels(), and var_label(), preventing false positives on label containers and preprocessing calls.
  5. Leading comments, preceding named arguments, and gt md()/html(): first_positional uses /expr[position() > 1][not(preceding-sibling::*[not(self::COMMENT)][1][self::EQ_SUB])][1], handling leading comments and preceding named arguments in scale_*() and guide_*(), and md and html are included in formatters.

The tests in lms/tests/testthat/test-hardcoded_label_linter.R, documentation in chapters/coding-practices/documenting-code.qmd and lms/README.md, lms/NAMESPACE, lms/R/default_linters.R, and generated .Rd files are consistent with the implementation and PR description.

Findings

None.

Verdict

All five Round 1 XPath findings are resolved in 12e7345962e18a6db549a8cfc3af5348bcda4945, with matching tests and documentation and no new defects found.

VERDICT: CLEAN

Reviewed-Commit: 12e7345

Posted by Claude Code (AI agent) --- not written by a human.

@d-morrison

Copy link
Copy Markdown
Contributor Author

Annotation dispositions for head 12e7345:

Check runs 136158420703,136158311405:

  • SUBMODULES_TOKEN is empty (notice): the submodules are public, so the anonymous clone worked.
  • Skipping element-level diff highlighting (notice): the preview diff hit its 500-element cap. This is informational; the rendered pages are unaffected.

Posted by Claude Code (AI agent) --- not written by a human.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

lms: lint hardcoded variable labels in plots and tables

2 participants