3

I have a dataframe with many columns ending in the same suffix, and I want to use rename_at() to remove them all, but I can't figure it out.

library(tidyverse)

my_df <- tibble(id = c(1, 2), 
jan_real = c(8, 10),
feb_real = c(9, 10),
mar_real = c(1, 11))

desired_df <- tibble(id = c(1, 2), 
jan = c(8, 10),
feb = c(9, 10),
mar = c(1, 11))
J.Sabree
  • 2,280
  • 19
  • 48

4 Answers4

6

You should now use rename_with() which superseded rename_at() from dplyr 1.0.0:

library(dplyr)

my_df %>%
  rename_with(~ sub("_real$", "", .x), everything())

# A tibble: 2 x 4
     id   jan   feb   mar
  <dbl> <dbl> <dbl> <dbl>
1     1     8     9     1
2     2    10    10    11

Using rename_at():

my_df %>%
  rename_at(vars(everything()), ~ sub("_real$", "", .x))
Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
3

You can try this approach

library(dplyr)
library(stringr)
my_df %>% 
  rename_at(vars(matches("_real")), ~str_remove(., "_real"))
#       id   jan   feb   mar
#     <dbl> <dbl> <dbl> <dbl>
# 1     1     8     9     1
# 2     2    10    10    11
Tho Vu
  • 1,304
  • 2
  • 8
  • 20
1

You can try gsub within setNames

desired_df <- setNames(my_df,gsub("_.*","",names(my_df)))

such that

> desired_df
# A tibble: 2 x 4
     id   jan   feb   mar
  <dbl> <dbl> <dbl> <dbl>
1     1     8     9     1
2     2    10    10    11
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

In base R, we can use trimws as well if we specify the whitespace as a regex to match the _ followed by characters (.*)

names(my_df) <- trimws(names(my_df), whitespace = "_.*")
my_df
# A tibble: 2 x 4
#     id   jan   feb   mar
#  <dbl> <dbl> <dbl> <dbl>
#1     1     8     9     1
#2     2    10    10    11
akrun
  • 874,273
  • 37
  • 540
  • 662