2013-04-29 43 views
1

假設我有興趣連接兩個變量。我開始用這樣的數據集:我們如何連接變量並在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 

回答

5

也許你正在尋找sprintf:由@joran提供

測試解決方案

sprintf("%05d",125) 
[1] "00125" 
> sprintf("%07d",125) 
[1] "0000125" 

如果你是填充字符串而不是整數,也許:

sprintf("%07s","125") 
[1] "0000125" 
+0

我沒有使用'sprintf(「%07s」,「125」)'因爲在我的系統上(Win R64)我得到了'[1]「125」' – 2013-04-29 15:19:49

+0

@ SimonO101這很不幸。 'sprintf'非常有用! – joran 2013-04-29 15:20:54

+0

謝謝@joran!我只是寫代碼,先轉換爲數字;奇蹟般有效! – 2013-04-29 15:23:06

3

或使用paste0pastepaste*被矢量化,所以你可以這樣做:

half <- paste(paste0("00",one), paste0("00",two) , sep = "-");head(half) 
#[1] "00125-0048593" "00125-0048593" "00125-0048593" "00125-0048593" 
#[5] "00125-0048593" "00125-0048593" 

但是你有不同的字符串寬度。另一種(sprintf沒有給我的系統上相同的結果)將與多個零,以粘貼比你知道你會需要,然後修剪到所需長度:

one <- paste0("0000000000000000",one) 
two <- paste0("0000000000000000",two) 
fst <- sapply(one , function(x) substring(x , first = nchar(x)-4 , last = nchar(x))) 
snd <- sapply(two , function(x) substring(x , first = nchar(x)-6 , last = nchar(x))) 
half <- paste(fst , snd , sep = "-");head(half) 

但我同意,這不是一個特別做事的好方法。如果我能用字符類數據獲得輸出,我會使用sprintf! (使用數字類)

+0

如果集合中的數字之一是「25」而你想要「00025」?我認爲'sprintf'在這種情況下更合適。 – A5C1D2H2I1M1N2O1R2T1 2013-04-29 15:10:22

+0

同意;這就是爲什麼我把99和125放在同一列,等等。我先試了一下,放棄了 - sprintf絕對是我在找的,謝謝! – 2013-04-29 15:13:02

+0

@AnandaMahto @hubert_farnsworth我已更新! 'sprintf'在我的系統上沒有提供相同的輸出!處理「字符」類的數據時,我得到了空間。 – 2013-04-29 15:26:07