Thank you @andresrcs ! You're absolutely right--this also works. I ended up needing a slightly different implementation (the function is going into a shiny app, and the users want to be able to specify the name of new joining variable).
This is what I am currently using:
create_join_column <- function(df, join_cols, by_col_name) {
# select join_cols
tmp <- select(df, all_of(join_cols))
# rename original data
join_col_data <- df
# assign new col with pmap_chr
join_col_data$new_col <- pmap_chr(.l = tmp, .f = paste, sep = "-")
# rename
names(join_col_data)[names(join_col_data) == "new_col"] <- by_col_name
# relocate
join_col_data <- relocate(join_col_data, all_of(by_col_name))
# return
return(join_col_data)
}
It's working for the moment, but now I'm curious how to use unite() and give a new column name:
library(tidyverse)
DFX <- data.frame(a = rep(LETTERS[1:5], 2),
b = sample(LETTERS[1:2], 10, replace = TRUE),
c = sample(LETTERS[1:5], 10, replace = TRUE),
x = 1:10,
y = rep(seq(2, 10, by = 2), 2),
z = sample(1:10, 10, replace = FALSE))
create_new_column <- function(data, cols, new_name) {
data %>%
unite(new_name, {{cols}}, remove = FALSE, sep = "-") %>%
relocate(new_name, everything())
}
create_new_column(data = DFX, cols = c('a', 'b'), new_name = "joincol")
#> new_name a b c x y z <- 'new_name' should be 'joincol'
#> 1 A-B A B B 1 2 10
#> 2 B-B B B E 2 4 2
#> 3 C-B C B C 3 6 5
#> 4 D-B D B B 4 8 9
#> 5 E-B E B D 5 10 6
#> 6 A-B A B D 6 2 4
#> 7 B-B B B C 7 4 3
#> 8 C-A C A C 8 6 8
#> 9 D-A D A C 9 8 7
#> 10 E-B E B D 10 10 1
unite() has that strange 'quasiquotation (you can unquote strings and symbols)' for the col argument, and I am at a loss for how to get this to work (I thought maybe any_of(), but no luck).
Thank you so much for the other answer (and don't feel obligated to respond--you've helped a ton!)
Cheers!