r - 使用 rename_all 从列名中删除数字

标签 r dplyr rename

我正在尝试从我拥有的某些列名称中删除数字。我尝试了以下方法,但没有成功。

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

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

数据:

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

最佳答案

由于作用域变体 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
# ...

关于r - 使用 rename_all 从列名中删除数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62657550/

相关文章:

r - 使用 R.zoo 绘制带有误差线的多个系列

r - 从日期时间更改为数字并返回到 R 中的日期时间

r - 用NA值找到POSIXct日期的最小或最大

windows - Golang os.Rename(<fromDir>,<toDir>) 在 Windows 中不起作用

eclipse - 当我重命名我的类时,我可以让 Eclipse 更改我的注释吗?

r - RStudio 控制台中的非英语(希伯来语)输出

r - 为什么在 Shiny 中出现 "subscript out of bounds"错误,但在 R 中却没有?

r - 通过组变量计算多个数值变量的百分比

r 使用 rms ols 函数处理多个对象和置信区间

c - 重命名功能?