lintr icon indicating copy to clipboard operation
lintr copied to clipboard

Dplyr: not detecting variables use with .env in mutate

Open latot opened this issue 1 year ago • 3 comments

Hi!, well, this is weird, seems lintr is not detecting when var are used inside mutate with .env, I have others .env in filter and works fine, the code is from examples of how to use roads networks in R.

  source_nodes <- nodes %>%
    dplyr::filter(.data$start_end == "start") %>%
    dplyr::pull(.data$nodeID)

  target_nodes <- nodes %>%
    dplyr::filter(.data$start_end == "end") %>%
    dplyr::pull(.data$nodeID)

  edges <- edges %>%
    dplyr::mutate(from = .env$source_nodes, to = .env$target_nodes)

Logs:

warning: [object_usage_linter] local variable ‘source_nodes’ assigned but may not be used
  source_nodes <- nodes %>%
  ^~~~~~~~~~~~
warning: [object_usage_linter] local variable ‘target_nodes’ assigned but may not be used
  target_nodes <- nodes %>%

Thx!

latot avatar Jul 25 '22 14:07 latot

If you remove .env, it should work fine. That construct is only necessary if there are name clashes between .data and .env.

AshesITR avatar Jul 26 '22 07:07 AshesITR

For further details, see: https://adv-r.hadley.nz/evaluation.html#quoting-and-ambiguity

IndrajeetPatil avatar Jul 26 '22 08:07 IndrajeetPatil

Hi, remember this all are examples, the problem it self, is the function is not detecting if a var is used or not, maybe for that particular case there is no problem and we can apply workaround removing the .env, but in other code that this will affects will not be the case, like the next one:

This code have the same result as the first one.

library(magrittr)
library(rlang)

f <- function(nodes, edges) {
  a <- nodes %>%
    filter(.data$n == 2)
  b <- nodes %>%
    filter(.data$n == 3)
  return(dplyr::mutate(
    edges,
    from = .data$a * .env$a,
    to = .data$b * .env$b))
}

Thx!

latot avatar Jul 26 '22 13:07 latot