This is a conceptual question.
How can we combine these two arguments .keep
and .before
in mutate()
while overwriting the column name with the same name:
The example (mtcars dataset):
We multiply carb
with mpg
then use .keep="unused"
to only keep the calculated carb
and move carb to position 2 by using .before=3
:
library(dplyr)
mtcars %>%
mutate(carb = carb * mpg, .keep = "unused", .before = 3)
carb
still remains at last position. and there is no error. Why?
In contrast using a new column name it works:
mtcars %>%
mutate(carb_new = carb * mpg, .keep = "unused", .before = 3)
How can I look behind the scenes to discover where the "problem" occurs? and should there not be a warning to not use the same name when using .keep
in mutate?
As most of the times the answer lies in the documentation. From ?mutate
Existing columns that are modified by ... will always be returned in their original location.
New columns created through ... will be placed according to the .before and .after arguments.