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

Handle non-vector sub-targets #1138

Closed
1 task done
wlandau opened this issue Jan 18, 2020 · 0 comments
Closed
1 task done

Handle non-vector sub-targets #1138

wlandau opened this issue Jan 18, 2020 · 0 comments

Comments

@wlandau
Copy link
Member

wlandau commented Jan 18, 2020

Prework

Description

#1105 made dynamic branching a breeze for most use cases, but now drake is less forgiving about non-vector sub-targets.

To quote Hadley in r-lib/vctrs#321:

vctrs is about vectors, not non-vectors

And I totally forgot about it in #1105.

library(drake)
library(gapminder)
library(tidyverse)

# Split the Gapminder data by continent.
gapminder_continents <- function() {
  gapminder %>%
    mutate(gdpPercap = scale(gdpPercap)) %>%
    split(f = .$continent)
}

# Fit a model to a continent.
fit_model <- function(continent_data) {
  lm(formula = gdpPercap ~ year, data = continent_data[[1]])
}

plan <- drake_plan(
  continents = gapminder_continents(),
  model = target(fit_model(continents), dynamic = map(continents))
)

make(plan)
#> target continents
#> dynamic model
#> subtarget model_23022788
#> subtarget model_e020ff00
#> subtarget model_53c1b086
#> subtarget model_0fc4392a
#> subtarget model_8b2d2fd5
#> aggregate model

readd(model)
#> Error: `..1` must be a vector, not a `lm` object

Created on 2020-01-18 by the reprex package (v0.3.0)

The error comes from trying to aggregate non-vectors.

x <- lm(mpg ~ cyl, data = mtcars)
y <- lm(mpg ~ wt, data = mtcars)
vctrs::vec_c(x, y)
#> Error : `..1` must be a vector, not a `lm` object

Created on 2020-01-18 by the reprex package (v0.3.0)

We need some special error handling to catch non-vectors.

safe_vec_c <- function(...) {
  tryCatch(
    vctrs::vec_c(x, y),
    vctrs_error_scalar_type = function(e) {
      list(x, y)
    },
    error = function(e) {
      stop(e)
    }
  )
}

x <- lm(mpg ~ cyl, data = mtcars)
y <- lm(mpg ~ wt, data = mtcars)

safe_vec_c(x, y)
#> [[1]]
#> 
#> Call:
#> lm(formula = mpg ~ cyl, data = mtcars)
#> 
#> Coefficients:
#> (Intercept)          cyl  
#>      37.885       -2.876  
#> 
#> 
#> [[2]]
#> 
#> Call:
#> lm(formula = mpg ~ wt, data = mtcars)
#> 
#> Coefficients:
#> (Intercept)           wt  
#>      37.285       -5.344

Created on 2020-01-18 by the reprex package (v0.3.0)

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

No branches or pull requests

1 participant