2015-11-11 80 views
1

假設我有這些向量:擴展矢量

g_number=c(3,2,4) 
g_names=c("b", "c", "d") 

我想創建一個基於g_number和g_names以下向量:

vnames=c("b.1", "b.2", "b.3", "c.1", "c.2", "d.1", "d.2", "d.3", "d.4") 

我想:

rep(g_names, g_number) 

但這些不會產生我想要的

回答

1

最後,我可以這樣做:

paste(rep(g_names, g_number), sequence(g_number), sep=".") 
+1

儘管如此,你會得到'c.2'和'd.3'。嘗試粘貼(rep(g_names,g_number),sequence(g_number),sep =「。」)'。 – Frank

2

我們可以嘗試

sprintf('%s.%d',rep(g_names, g_number),sequence(g_number)) 
3

我會去用@ akrun的建議,但你也可以嘗試像:

make.unique(c(g_names, rep(g_names, g_number)))[-seq_along(g_names)] 
# [1] "b.1" "b.2" "b.3" "c.1" "c.2" "d.1" "d.2" "d.3" "d.4" 

的基本思路是對rep的結果使用make.unique。但是,由於make.unique將具有裸露的第一個值(不帶數字),因此我們將「g_names」值添加到由rep創建的向量中,然後刪除裸值。

+0

我從@JoshO'Brien得到了這個把戲,但我不記得從哪裏...... – A5C1D2H2I1M1N2O1R2T1

+0

不錯。我試圖弄清楚如何讓'unique.names'在這裏工作。也許你在這裏? http://stackoverflow.com/a/19396664/1191259 – Frank

+1

@Frank,看起來像。啊,是的,我的愚蠢的「喬剃鬚」評論.... – A5C1D2H2I1M1N2O1R2T1