In dplyr, how to delete and rename columns that don't exist, manipulate all names, and name a new variable using a string?

  1. I would use setNames for this:

iris %>% setNames(make.names(names(.)))

  1. Include everything() as an argument for select:

iris %>% select(-matches("Width"), everything())
iris %>% select(-matches("X"), everything())

  1. To my understanding there's no other shortcut than explicitly naming the string like you already do:

iris %>% mutate_("newcol" = 0)


I came up with the following solution for #4:

iris %>% 
  rename_at(vars(everything()), 
            function(nm)
              recode(nm, 
                     Sepal.Length="sl",
                     Sepal.Width = "sw",
                     X = "Y")) %>%
  head()

The last line just for convenient output of course.

Tags:

R

Dataframe

Dplyr