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

sql_case_when() doesn't support unevaluated formulas #184

Closed
lionel- opened this Issue Nov 20, 2018 · 4 comments

Comments

Projects
None yet
2 participants
@lionel-
Copy link
Member

lionel- commented Nov 20, 2018

Reprex from @FrancoisGuillem in tidyverse/dplyr#3936

library(RSQLite)
library(rlang)
library(dplyr)

con <- dbConnect(SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)

mtcars_remote <- tbl(con, "mtcars")

# Works
labels <- c("low", "mid", "high")
breaks <- c(2, 4)

cases <- lapply(seq_along(breaks), function(i) {
  expr(carb <= breaks[!!i] ~ labels[!!i])
})

cases <- append(cases, expr(TRUE ~ labels[length(labels)]))

mtcars %>% mutate(cg = case_when(!!!cases))
## => works
mtcars_remote %>% mutate(cg = case_when(!!!cases))
## Error in eval_bare(call, env) : 
##   'rho' must be an environment not NULL: detected in C-level eval
@lionel-

This comment was marked as resolved.

Copy link
Member

lionel- commented Nov 20, 2018

Simpler reprex:

library(RSQLite)
library(rlang)
library(dplyr)

con <- dbConnect(SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)
mtcars_remote <- tbl(con, "mtcars")

fs1 <- exprs(
  cyl == 4 ~ TRUE,
  TRUE     ~ FALSE
)

x <- 4
fs2 <- exprs(
  cyl == x ~ TRUE,
  TRUE     ~ FALSE
)

mtcars_remote %>% mutate(case_when(!!!fs1)) %>% pull()
#> [1] 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 0 0 0 1

mtcars_remote %>% mutate(case_when(!!!fs2)) %>% pull()
#> Error: Can't extract an environment from NULL

@hadley hadley added this to the v1.2.2 milestone Jan 2, 2019

@hadley

This comment has been minimized.

Copy link
Member

hadley commented Jan 2, 2019

Are there other changes to dplyr::case_when() that I should know about?

@hadley

This comment has been minimized.

Copy link
Member

hadley commented Jan 2, 2019

Slightly even more simple reprex:

library(dplyr, warn.conflicts = FALSE)

mf <- dbplyr::memdb_frame(abc = 1:10)

fs1 <- rlang::exprs(
  abc == 4 ~ TRUE,
  TRUE     ~ FALSE
)
mf %>% mutate(case_when(!!!fs1)) %>% pull()
#>  [1] 0 0 0 1 0 0 0 0 0 0

x <- 4
fs2 <- rlang::exprs(
  abc == x ~ TRUE,
  TRUE     ~ FALSE
)
mf %>% mutate(case_when(!!!fs2)) %>% pull()
#> Error: Can't extract an environment from NULL

Created on 2019-01-02 by the reprex package (v0.2.1)

@hadley

This comment has been minimized.

Copy link
Member

hadley commented Jan 2, 2019

Even simpler reprex:

partial_eval(expr(~ x))
#> Error: Can't extract an environment from NULL

@hadley hadley closed this in 790506e Jan 2, 2019

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