I have iris dataframe, I want a function that create/replace a new/existing column by combining others, this function has 2 parameters : name of the new column and names of columns to combine.
for example I want to combine Petal.Width and Species : I tried :
func <- function(data, names, column_names){
data <- data %>% mutate_at(vars(column_names), names = paste0(column_names))
}
iris <- func(iris, "Petal.Width", c("Petal.Width","Species"))
Honestly I don't know how to deal with variables that must be considered like names.
The result should be :
iris$Petal.Width <- paste0(iris$Petal.Width, iris$Species)
Do you have an idea?
CodePudding user response:
You can use rlang::syms
to convert your character values to symbols. And then can use !!!
and :=
to inject them into the call
func <- function(data, names, column_names){
column_names <- syms(column_names)
data %>% mutate("{names}" := paste0(!!!column_names))
}
func(iris, "Petal.Width", c("Petal.Width","Species"))
For more suggestions on creating your own functions that use dplyr
, see the programming with dplyr guide