Home > Enterprise >  Remove all the characters after a '_' in column name of r dataframe
Remove all the characters after a '_' in column name of r dataframe

Time:12-03

I have a dataframe as follows :

   Ax_ghx By_jkgf YTz8_hjks gh3_hjhd
a  1  2  3  4
b  3  4  5  6

How to remove all the characters after '_' which results in a dataframe as follows :

  Ax By YTz8 gh3
a 1  2  3  4
b 3  4  5  6

CodePudding user response:

Data example

 df <- data.frame(Ax_ghx = 1, By_jkgf = 1, YTz8_hjks = 1,gh3_hjhd = 1)   

Tidyverse approach

library(dplyr)  


df %>% rename_with(.fn = ~sub(x = .,"_.*",""))

  Ax By YTz8 gh3
1  1  1    1   1

Base R

names(df) <- sub(x = names(df),"_.*","")

df 
              
  Ax By YTz8 gh3
1  1  1    1   1
  • Related