Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming columns excluding a certain set of columns

Tags:

r

rename

dplyr

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?

like image 613
Ric S Avatar asked Nov 18 '25 10:11

Ric S


1 Answers

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

like image 200
akrun Avatar answered Nov 20 '25 01:11

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!