【问题标题】:rename all columns dynamically with same name and numerical suffix使用相同的名称和数字后缀动态重命名所有列
【发布时间】:2020-09-14 15:58:45
【问题描述】:

我想将所有以 S 开头的列重命名为这种格式:

原始列名

> colnames(df)
[1] "ID" "S31"         "S32"         "S33"         "S42"  

到这里:

> colnames(df)
[1] "id" "common_name_1"         "common_name_2"         "common_name_3"         "common_name_4" 

我尝试使用 mutate_at 但我找不到生成自动增加后缀的方法... 谢谢

【问题讨论】:

    标签: r dplyr rename


    【解决方案1】:

    你可以使用rename_at

    library(dplyr)
    df %>% rename_at(vars(starts_with('S')), ~paste0('common_name_', seq_along(.)))
    

    使用base R,我们可以使用startsWith

    cols <- startsWith(names(df), 'S')
    df[cols] <- paste0('common_name_', seq_len(sum(cols)))
    

    或者grep

    cols <- grep('^S', names(df))
    df[cols] <- paste0('common_name_', seq_along(cols))
    

    【讨论】:

    • 完美,谢谢,很有帮助 我不知道 seq_along()
    【解决方案2】:

    我们也可以使用grepl

    cols <- grepl('^S', names(df))
    df[cols] <- paste0('common_name_', seq_len(sum(cols)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 2019-05-12
      • 1970-01-01
      • 2016-01-04
      相关资源
      最近更新 更多