I noticed an unexpected behavior of mutate_at. Suppose I have a data frame and a list of columns I want to mutate, like:
df1 <- data_frame(var1 = c(1,2,3,4,5,6),
var2 = c(1,1,1,2,2,2),
var3 = c(10,30,50,70,90,110))
variables <- c("var1", "var2")
I now apply mutate_at to create new factor versions of the columns defined in variables. By specifying "cat" in list, I am making sure the old versions are kept, and the new versions have the name of the old version plus "_cat":
df1 %>% mutate_at(vars(variables), .funs = list(cat = as.factor))
# A tibble: 6 x 5
var1 var2 var3 var1_cat var2_cat
<dbl> <dbl> <dbl> <fct> <fct>
1 1 1 10 1 1
2 2 1 30 2 1
3 3 1 50 3 1
4 4 2 70 4 2
5 5 2 90 5 2
6 6 2 110 6 2
However, if I apply mutate_at to only one column (in my case, my variables vector has only one element), the name of the new variable is only "cat":
variables <- c("var1")
df1 %>% mutate_at(vars(variables), .funs = list(cat = as.factor))
# A tibble: 6 x 4
var1 var2 var3 cat
<dbl> <dbl> <dbl> <fct>
1 1 1 10 1
2 2 1 30 2
3 3 1 50 3
4 4 2 70 4
5 5 2 90 5
6 6 2 110 6
On some level, I understand why mutate_at is doing this: If you want to name one mutated column in any special way, just use mutate like mutate(var1_cat = as.factor(var1)).
However, in my case, I want to run the mutate_at operation over a number of data frames, for each of which I have a vector of columns to change. Crucially, these vectors might have only one element. So, would it not be better for mutate_at to show the same naming behavior no matter how many vars it receives?