Renaming columns excluding a certain set of columns

Viewed 153

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?

3 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

one_of() could be the most natural way to do it, however, a possibility could also be:

iris %>%
 rename_at(vars(which(!names(.) %in% 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

Because dplyr errors out when it cannot find columns Foo and Fii in iris, we must find a way to avoid looking for them. Try dplyr::setdiff():

library(dplyr)
library(stringr)

untouch_vars <- c("Sepal.Length", "Species", "Foo", "Fii")

iris %>% 
  rename_at(setdiff(names(.), untouch_vars), ~str_c("HEY_", .)) %>% 
  names()
Related