假設我有興趣連接兩個變量。我開始用這樣的數據集:我們如何連接變量並在R中添加前導零?
#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("00"),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"
也就是說,我希望連接的第一部分有五位數字,第二部分有七位數字,並在適用時應用前導零。
我應該先轉換數據集以添加前導零,然後執行粘貼命令嗎?或者我可以在同一行代碼中完成這一切嗎?我放了一個data.table()
標籤,因爲我確定有一個非常有效的解決方案,我根本不知道。
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
我沒有使用'sprintf(「%07s」,「125」)'因爲在我的系統上(Win R64)我得到了'[1]「125」' – 2013-04-29 15:19:49
@ SimonO101這很不幸。 'sprintf'非常有用! – joran 2013-04-29 15:20:54
謝謝@joran!我只是寫代碼,先轉換爲數字;奇蹟般有效! – 2013-04-29 15:23:06