在 R 编程中为向量的元素添加前导零 - 使用 paste0() 和 sprintf()函数
R 语言中的paste0()和sprintf()函数也可用于将前导零添加到作为参数传递给它的向量的每个元素。
Syntax:
paste0(“0”, vec)
or
sprintf(“%0d”, vec)
Parameters:
paste0: It will add zeros to vector
sprintf: To format a vector(adding zeros)
vec: Original vector data
Returns: Vectors by addition of leading zeros
示例 1:
r
# R Program to add leading zeros
# Create example vector
vec <- c(375, 21, 1, 7, 0)
vec
# Add leading zeros
vec_0 <- paste0("0", vec)
vec_0
r
# R Program to add leading zeros
# Create example vector
vec <- seq(5)
# Add leading zeros
sprintf("sequence_%03d", vec)
输出 :
[1] 375 21 1 7 0
[1] "0375" "021" "01" "07" "00"
示例 2:
r
# R Program to add leading zeros
# Create example vector
vec <- seq(5)
# Add leading zeros
sprintf("sequence_%03d", vec)
输出 :
[1] "sequence_001" "sequence_002" "sequence_003" "sequence_004" "sequence_005"