【问题标题】:How to replace column names that include specific string r如何替换包含特定字符串 r 的列名
【发布时间】:2020-06-16 18:56:39
【问题描述】:

我想用预定义的名称替换包含“score”字符串的列。

这是一个简单的示例数据集和我想要替换的列名。

df1 <- data.frame(a = c(1,2,3,4,5),
                  b = c(5,6,7,8,9),
                  c.1_score = c(10,10,2,3,4),
                  a.2_score= c(1,3,5,6,7))

replace.cols <- c("c_score", "a_score")

每次试验的列数都会发生变化。因此,只要列名包含_score,我想用我预定义的replace.cols 名称替换它们。

所需的列名称应为a b c_score and a_score

有什么想法吗? 谢谢。

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    我们可以使用rename_at

    library(dplyr)
    df1 <- df1 %>%
              rename_at(vars(ends_with('score')), ~ replace.cols)
    
    df1
    #  a b c_score a_score
    #1 1 5      10       1
    #2 2 6      10       3
    #3 3 7       2       5
    #4 4 8       3       6
    #5 5 9       4       7
    

    str_remove

    library(stringr)
    df1 %>%
         rename_at(vars(ends_with('score')), ~ str_remove(., '\\.\\d+'))
    

    或者使用base R(假设列名顺序在'replace.cols'中维护)

    names(df1)[endsWith(names(df1), 'score')] <- replace.cols
    

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 2011-07-15
      • 1970-01-01
      • 2023-03-20
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多