We can use rename_with to rename columns with a function (stringr functions, for example).
Consider the following data df_1:
df_1 <- data.frame( x = replicate(n = 3, expr = rnorm(n = 3, mean = 10, sd = 1)), y = sample(x = 1:2, size = 10, replace = TRUE) ) names(df_1) #[1] "x.1" "x.2" "x.3" "y"
Rename all variables with dplyr::everything():
library(tidyverse) df_1 %>% rename_with(.data = ., .cols = everything(.), .fn = str_replace, pattern = '.*', replacement = str_c('var', seq_along(.), sep = '_')) %>% names() #[1] "var_1" "var_2" "var_3" "var_4"
Rename by name particle with some dplyr verbs (starts_with, ends_with, contains, matches, ...).
Example with . (x variables):
df_1 %>% rename_with(.data = ., .cols = contains('.'), .fn = str_replace, pattern = '.*', replacement = str_c('var', seq_along(.), sep = '_')) %>% names() #[1] "var_1" "var_2" "var_3" "y"
Rename by class with many functions of class test, like is.integer, is.numeric, is.factor...
Example with is.integer (y):
df_1 %>% rename_with(.data = ., .cols = is.integer, .fn = str_replace, pattern = '.*', replacement = str_c('var', seq_along(.), sep = '_')) %>% names() #[1] "x.1" "x.2" "x.3" "var_1"
The warning:
Warning messages: 1: In stri_replace_first_regex(string, pattern, fix_replacement(replacement), : longer object length is not a multiple of shorter object length 2: In names[cols] <- .fn(names[cols], ...) : number of items to replace is not a multiple of replacement length
It is not relevant, as it is just an inconsistency of seq_along(.) with the replace function.
drop=TRUEdefault argument to[, which causes a "1-column" object to be converted to a vector... and vectors don't havecolnames. An example of what you tried would be very helpful.