r-根据值的长度在值的开头添加一个数字

  • 本文关键字:数字 添加 一个 开头 r dplyr
  • 更新时间 :
  • 英文 :


根据以下数据,如果值的长度小于9,我如何告诉R在值(列key(的开头添加0

样本数据:

id = c(1,2,3,4,5,6,7,8,9,10)
Key = c("10032012", "10812012", "2073017", "10692013", "10892012", "10952014", "10972012", "560392013", "560372013", "56022012")
df = data.frame(id, Key)

期望输出:

df_desired = structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), Key = c("010032012", 
"010812012", "02073017", "010692013", "010892012", "010952014", "010972012", 
"560392013", "560372013", "56022012")), class = "data.frame", row.names = c(NA, 
-10L))

一些答案对于任何字符串:

df$Key <- ifelse(nchar(df$Key) < 9, paste0("0", df$Key), df$Key)

如果它们都是整数字符串,则规范的方法是:

df$Key <- sprintf("%09d", as.integer(df$Key)) 

使用CCD_ 5&stringr

library(dplyr)
library(stringr)
df_desired <- df %>% mutate(Key = str_pad(Key, width = 9, pad = "0"))

最新更新