【问题标题】:Remove all the characters after a '_' in column name of r dataframeRemove all the characters after a \'_\' in column name of r dataframe
【发布时间】:2022-12-02 11:11:19
【问题描述】:

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

【问题讨论】:

    标签: r dataframe gsub


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-26
      • 2023-02-09
      • 2023-02-25
      • 2020-08-25
      • 1970-01-01
      • 2022-12-02
      • 2022-12-02
      • 2022-12-27
      相关资源
      最近更新 更多