I have a data frame, that I filter, drop and add some columns and than I would like to rename all of columns, all using pipes (%>%
).
However, I don't understand how to take a current colnames vector (within %>%
) and replace it with another vector? If I would not drop columns, it seems pretty easy, but how to "update" the vector of colnames
within a chain of pipes?
library(dplyr)
library(tidyr)
data("mtcars")
mtcars %>%
filter(disp < 200) %>%
dplyr::select(-c('mpg','cyl', "disp")) %>%
mutate(Type = 2) %>%
# rename_at(vars(names(df), # how to rename the columns???
# function(x) paste(names(df), "new", sep = "_"))) %>%
head(2)
What I get:
hp drat wt qsec vs am gear carb Type
1 110 3.9 2.620 16.46 0 1 4 4 2
2 110 3.9 2.875 17.02 0 1 4 4 2
What I expect (changed colnames)
hp_new drat_new wt_new qsec_new vs_new am_new gear_new carb_new Type_new
1 110 3.9 2.620 16.46 0 1 4 4 2
2 110 3.9 2.875 17.02 0 1 4 4 2