You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R的dplyr中为多列添加前导零的实现方法

使用dplyr批量为多列添加前导零

原数据构造

x <- c("001", "2", "32")
y <- c("04", "455", "6")
X <- data.frame(cbind(x,y), stringsAsFactors = FALSE)

期望结果

x   y
1 001 004
2 002 455
3 032 006

正确的dplyr实现方案

dplyr提供两种常用写法,适配不同版本:

方法1:使用mutate_at(适配旧版dplyr)

可以通过自定义函数或匿名函数实现批量处理:

library(dplyr)

lead_cols <- c("x", "y")

# 自定义函数写法
lead_zeros <- function(col) {
  sprintf("%03d", as.numeric(col))
}
X <- X %>% mutate_at(vars(lead_cols), lead_zeros)

# 更简洁的匿名函数写法
X <- X %>% mutate_at(vars(lead_cols), ~sprintf("%03d", as.numeric(.x)))

方法2:使用across(dplyr 1.0.0及以上版本推荐)

across是dplyr新版本推荐的批量列处理函数,语法更统一:

X <- X %>% mutate(across(all_of(lead_cols), ~sprintf("%03d", as.numeric(.x))))

原代码错误原因

你之前的代码报错是因为两个核心问题:

  1. mutate_at的第二个参数需要传入函数或函数式表达式,但你直接执行了sprintf("%03d", as.numeric(lead_cols))——lead_cols是列名字符向量,as.numeric(lead_cols)会把非数值字符串转成NA,同时mutate_at无法识别这个计算结果为函数,导致报错。
  2. dplyr的mutate系列函数直接返回修改后的数据集,无需用X[lead_cols] <-这种base R风格的赋值方式,直接将结果重新赋值给X即可。

验证结果

执行上述代码后,打印X即可得到期望的带前导零的结果:

print(X)

内容的提问来源于stack exchange,提问作者David Crow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:20:35