I have made a function which mutates across columns and creates new named columns from each of them. The new colums are put to the right side of the dataframe whereas I would like to have them adjacent to each of the original columns. I am looking for a solution that will generalise to any dataframe this function might be used on, writing a select statement to reorder the columns is not automatic enough for my use case.
test_data <- data.frame(data_col_1 = c(1,2,3),
data_col_2 = c(1,2,3),
data_col_3 = c(1,2,3),
another_column = c("a","b","c"))
perc_funct <- function(df, columns, numerator){
p_f <- function(x, numerator){
(x/numerator)*100
}
j <- df %>%
mutate( across({{columns}},
.fns = list(perc = ~p_f(.x, numerator)),
.names = "{col}_{fn}"))# need to figure out a way to get the columns ordered
return(j)
}
test_data %>% perc_funct(columns = starts_with("data"), numerator = 1)
The output currently puts all the new colums to the right.
"data_col_1" "data_col_2" "data_col_3" "another_column" "data_col_1_perc" "data_col_2_perc" "data_col_3_perc"
The output I want puts each new colums to the right of each old column. "data_col_1" "data_col_1_perc" "data_col_2" "data_col_2_perc" "data_col_3" "data_col_3_perc" "another_column"