我们需要首先将其转换为numeric
并使用sprintf
df1$col1 <- sprintf("%02d", as.numeric(df1$col1))
df1$col1
#[1] "01" "01" "02" "01" "03" "03" "04" "04"
如果它是一个factor
列,首先转换为character
在前往之前numeric
df1$col1 <- sprintf("%02d", as.numeric(as.character(df1$col1)))
如果包含字母
df1$col1 <- c(1, '01', 2, '01', 3, 'A', 4, '04')
i1 <- grepl("^[0-9]$", df1$col1)
df1$col1[i1] <- paste0("0", df1$col1[i1])
df1$col1
#[1] "01" "01" "02" "01" "03" "A" "04" "04"
data
df1 <- data.frame(col1 = c(1, '01', 2, '01', 3, '03', 4, '04'), stringsAsFactors=FALSE)