2 つの変数を連結することに関心があるとします。次のようなデータセットから始めます。
#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
簡単な貼り付けコマンドでうまくいきます。
#half way there
half <- paste(one,two,sep="-");head(half)
[1] "125-48593" "125-48593" "125-48593" "125-48593" "125-48593" "125-48593"
しかし、実際には次のようなデータセットが必要です。
#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
そのため、単純な貼り付けコマンドで次のようになります。
#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"
つまり、連結の最初の部分が 5 桁、2 番目の部分が 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