vroom icon indicating copy to clipboard operation
vroom copied to clipboard

Create multiple columns of the same type

Open mgirlich opened this issue 4 years ago • 1 comments

It would be great to make it easier to define multiple columns of the same type to avoid repetition. For example something along the line

    library(vroom)

    fct_cols <- c("success", "attempts")
    yr_cols <- c("birthyr", "firstyr")
    mdy_cols <- c("birthdy")
    chr_cols <- c("name")

    cols_of <- function(col_format, names) {
      col_spec <- rep_len(list(col_format), length.out = length(names))
      setNames(col_spec, names)
    }

    col_spec_list <- c(
      cols_of(col_character(), chr_cols),
      cols_of(col_factor(), fct_cols),
      cols_of(col_date(format = "%Y"), yr_cols),
      cols_of(col_date(format = "%m/%d/%Y"), mdy_cols)
    )
    cols_only(!!!col_spec_list)
    #> cols_only(
    #>   name = col_character(),
    #>   success = col_factor(levels = NULL, ordered = FALSE, include_na = FALSE),
    #>   attempts = col_factor(levels = NULL, ordered = FALSE, include_na = FALSE),
    #>   birthyr = col_date(format = "%Y"),
    #>   firstyr = col_date(format = "%Y"),
    #>   birthdy = col_date(format = "%m/%d/%Y")
    #> )

<sup>Created on 2020-10-26 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)</sup>

It is already quite easy to do but it would be great to export a function for this or at least document it. If you like the idea I'm happy to add a PR (and one might also want to add that to readr).

PS: I discovered an issue for using the tidyselect helpers: https://github.com/tidyverse/readr/issues/237 which would also be very nice to have. Unfortunately, it doesn't seem like it is currently worked on. Is this still something on the roadmap?

mgirlich avatar Oct 26 '20 09:10 mgirlich

I will be thinking about colspec matters soon, so I'm leaving this open as an interesting idea and example. But no promises re: exactly what will happen.

jennybc avatar Mar 25 '22 20:03 jennybc