I'm curious if there's a way to programmatically assign the into
argument of tidyr::separate
based on the col
argument. The data I receive (a sample is below!) often contains hyphenated columns like "GP-GS" or "sb-att".
library(tidyverse)
test <- tribble(~Player, ~"gp-gs", ~ab, ~"sb-att",
"A", "16-16", 68, "6-9",
"B", "10-6", 26, "0-1",
"C", "14-9", 69, "5-9",
)
My first thought was to create a new function separate2
and use that:
separate2 <- function(data, col, ...) {
separate(data, col,
into = c(str_extract(col, "^[^-]+"),
str_extract(col,"[^-]+$")),
sep = "[-]+",
extra = "merge")
}
separate2(test,"gp-gs")
While this works, col
must be quoted for it to work. Tidyeval may be a means to providing functionality similar to tidyr::separate
, but I'm unsure where to begin.
As a bonus question: how might one apply the new separate2
function to all columns containing a hyphen (as opposed to explicitly naming the columns, which are inconsistently named across data sources)? A for
loop certainly works, but is there a more "tidy" solution?
for (col in str_subset(names(test),"-")) {
test <- separate2(test,col)
}
Thanks in advance!