Hello everyone! Thank you in advance for taking the time to read and help with this I have a somewhat esoteric problem that I've somewhat solved, but I am positive there is a better way to do it...
I want to write a function that takes any existing columns in a data.frame
/tibble
and combines them into a new column, separated by -
I have the following data frame:
library(dplyr)
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))
DFX
The function I've written can handle up to 3 columns (which I determine using some basic control flow), but I am wondering if there is another handy combination of .data[[cols]]
and maybe stringr
or glue
?
create_new_column <- function(data, cols) {
if (length(cols) == 3) {
return_data <- mutate(data,
new_col = paste(
.data[[cols[1]]], .data[[cols[2]]],
.data[[cols[3]]], sep = "-"))
} else if (length(cols) == 2) {
return_data <- mutate(data,
new_col = paste(
.data[[cols[1]]], .data[[cols[2]]], sep = "-"))
} else {
return_data <- mutate(data,
new_col = paste(.data[[cols[1]]], sep = "-"))
}
return(return_data)
}
# test
create_new_column(data = DFX, cols = c("b", "c"))
create_new_column(data = DFX, cols = c("b", "c" , "y"))
Thanks again in advance!