remove suffix from column names using rename_at in r
Asked Answered
P

4

5

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))
Priscella answered 1/9, 2020 at 22:55 Comment(0)
D
7

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))
Deflected answered 1/9, 2020 at 22:59 Comment(0)
M
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
Mizuki answered 2/9, 2020 at 1:33 Comment(0)
B
0

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
Baroque answered 1/9, 2020 at 22:58 Comment(0)
B
0

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
Beare answered 1/9, 2020 at 23:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.