Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

if_any() does not work as expected inside mutate when no inputs are provided #7077

Open
ks8997 opened this issue Aug 27, 2024 · 2 comments
Open

Comments

@ks8997
Copy link

ks8997 commented Aug 27, 2024

This is related to #7074. if_any() is now supposed to return FALSE when no inputs are provided as per #7072. This works correctly inside filter but not mutate.

iris %>% 
  filter(if_any(c(), \(x) x  > 4000)) # returns no rows as expected

iris %>%
    mutate(z = if_any(c(),  \(x) x  > 4000)) # incorrectly returns all TRUE

Apologies if I misunderstood something.

@DavisVaughan
Copy link
Member

Yea I think you're right, I didn't double check for mutate(). Thanks for following up!

@ks8997
Copy link
Author

ks8997 commented Sep 1, 2024

@DavisVaughan So I poked around a bit and I think the fix seems straightforward. The problematic section is the below chunk in if_across():

dplyr/R/across.R

Lines 345 to 347 in 0005f67

if (!length(df)) {
return(TRUE)
}

This unconditionally returns TRUE for empty inputs.

My proposed fix is:

if_across <- function(op, df) {
  n <- nrow(df)
  across_if_fn <- context_peek_bare("across_if_fn")

  if (!length(df)) {
    if (across_if_fn == "if_any") {
      return(FALSE)
    } else {
      return(TRUE)
    }
  }
    
  combine <- function(x, y) {
    if (is_null(x)) {
      y
    } else {
      op(x, y)
    }
  }
  reduce(df, combine, .init = NULL)
}

The across_if_fn stores information about the type of across function we are calling. It will then returnFALSE for if_any() and TRUE for if_all(). The rest of the function is unchanged. New to this but happy to submit a PR if this solution looks alright to you. I'll also add a test case.

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

No branches or pull requests

2 participants