【问题标题】:Using rename_all to remove numbers from column names使用 rename_all 从列名中删除数字
【发布时间】:2020-10-20 18:18:33
【问题描述】:

我正在尝试从我拥有的某些列名中删除数字。我试过以下没有运气。

iris %>% 
  rename_all(.funs = list(gsub('[[:digit:]]+', "", names(.))))

如何使用rename_all 正确删除列名中的数字?

数据:

data(iris)
numericNames <- paste(seq(1:5), colnames(iris), sep = "")
colnames(iris) <- numericNames

【问题讨论】:

    标签: r dplyr rename


    【解决方案1】:

    由于范围变体rename_all 已被dplyr 1.0.0 版取代,您应该像这样使用rename_with

    iris %>% 
      rename_with(~gsub("\\d+", "", .))
    

    或者,使用您使用的正则表达式

    iris %>% 
      rename_with(~gsub('[[:digit:]]+', "", .))
    

    . 指的是列名,所以不需要使用names(.)

    输出

    #     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    # 1            5.1         3.5          1.4         0.2     setosa
    # 2            4.9         3.0          1.4         0.2     setosa
    # 3            4.7         3.2          1.3         0.2     setosa
    # ...
    

    【讨论】:

      【解决方案2】:

      rename_all 中直接传递列名。

      library(dplyr)
      iris %>%  rename_all(~gsub('[[:digit:]]+', "", .)) %>% head
      
      #  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
      #1          5.1         3.5          1.4         0.2  setosa
      #2          4.9         3.0          1.4         0.2  setosa
      #3          4.7         3.2          1.3         0.2  setosa
      #4          4.6         3.1          1.5         0.2  setosa
      #5          5.0         3.6          1.4         0.2  setosa
      #6          5.4         3.9          1.7         0.4  setosa
      

      【讨论】:

        猜你喜欢
        • 2018-02-08
        • 1970-01-01
        • 2019-01-06
        • 1970-01-01
        • 1970-01-01
        • 2018-06-01
        • 2013-04-20
        • 2017-08-03
        • 1970-01-01
        相关资源
        最近更新 更多