我们如何连接变量并在R中添加前导零?

hub*_*rth 1 r string-concatenation

假设我有兴趣连接两个变量.我从这样的数据集开始:

#what I have
A <- rep(paste("125"),50)
B <- rep(paste("48593"),50)
C <- rep(paste("99"),50)
D <- rep(paste("1233"),50)

one <- append(A,C)
two <- append(B,D)

have <- data.frame(one,two); head(have)
  one   two
1 125 48593
2 125 48593
3 125 48593
4 125 48593
5 125 48593
6 125 48593
Run Code Online (Sandbox Code Playgroud)

一个简单的粘贴命令可以解决这个问题:

#half way there
half <- paste(one,two,sep="-");head(half)
[1] "125-48593" "125-48593" "125-48593" "125-48593" "125-48593" "125-48593"
Run Code Online (Sandbox Code Playgroud)

但我实际上想要一个看起来像这样的数据集:

#what I desire
E <- rep(paste("00125"),50)
F <- rep(paste("0048593"),50)
G <- rep(paste("00099"),50)
H <- rep(paste("0001233"),50)

three <- append(E,G)
four <- append(F,H)

desire <- data.frame(three,four); head(desire)
  three    four
1 00125 0048593
2 00125 0048593
3 00125 0048593
4 00125 0048593
5 00125 0048593
6 00125 0048593
Run Code Online (Sandbox Code Playgroud)

这样简单的粘贴命令就会产生这样的结果:

#but what I really want
there <-  paste(three,four,sep="-");head(there)
[1] "00125-0048593" "00125-0048593" "00125-0048593" "00125-0048593"
[5] "00125-0048593" "00125-0048593"
Run Code Online (Sandbox Code Playgroud)

也就是说,我希望串联的第一部分有五个数字,第二部分有7个数字,适用时会应用前导零.

我应该首先转换数据集以添加前导零,然后执行粘贴命令吗?或者我可以在同一行代码中完成所有操作吗?我放了一个data.table()标签,因为我确信那里有一个非常有效的解决方案,我根本不知道.

@joran提供的测试解决方案:

one <- sprintf("%05s",one)
two <- sprintf("%07s",two)
have <- data.frame(one,two); head(have)
    one     two
00125 0048593
00125 0048593
00125 0048593
00125 0048593
00125 0048593
00125 0048593
desire <- data.frame(three,four); head(desire)
  three    four
00125 0048593
00125 0048593
00125 0048593
00125 0048593
00125 0048593
00125 0048593

identical(have$one,desire$three)
[1] TRUE
identical(have$two,desire$four)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)

jor*_*ran 5

也许您正在寻找sprintf:

sprintf("%05d",125)
[1] "00125"
> sprintf("%07d",125)
[1] "0000125"
Run Code Online (Sandbox Code Playgroud)

如果你填充字符串而不是整数,可能:

sprintf("%07s","125")
[1] "0000125"
Run Code Online (Sandbox Code Playgroud)