I would like to add a prefix to the columns of my dataset if the column names are not contained in a character vector called untouch_vars.
After looking at the help page of rename_at, I tried the following lines of code:
data("iris")
untouch_vars <- c("Sepal.Length", "Species", "Foo", "Fii")
iris %>%
rename_at(vars(-untouch_vars), ~str_c("HEY_", .))
but it doesn't work since Foo and Fii are not present in the iris dataset. In fact, I get the following error:
Error: Unknown columns `Foo` and `Fii`
Call `rlang::last_error()` to see a backtrace
Since I have several datasets and I do not want to create a custom vector of to-be-excluded variables for each of them, is there a way to make my intent happen?
We can use either one_of
iris %>%
rename_at(vars(-one_of(untouch_vars)), ~ str_c("HEY_", .)) %>%
head(2)
# Sepal.Length HEY_Sepal.Width HEY_Petal.Length HEY_Petal.Width Species
#1 5.1 3.5 1.4 0.2 setosa
#2 4.9 3.0 1.4 0.2 setosa
There would be a warning message of unknown columns 'foo', 'Fii'
or with setdiff
iris %>%
rename_at(vars(setdiff(names(.), untouch_vars)), ~str_c("HEY_", .))
there won't be any warnings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With