2014-08-28 209 views
0

我有一個載體 Names<-c("A", "B", "C")多串粘貼到一個字符串

而且我會最終像這樣的事情
c("A_Mean", "A_Median", "A_InGroupVar", "B_Mean", "B_Median", "B_InGroupVar", "C_Mean", "C_Median", "C_InGroupVar")

我曾嘗試粘貼功能 c(paste(Names, "_Mean"), paste(Names, "_Median"), paste(Names, "_InGroupvar"))

但我需要的矢量按名稱排序。我知道我可以輕鬆地做到這一點,但我正在尋找更優雅的解決方案。

回答

3

這裏是一個原始的辦法:

Names <- rep(c("A", "B", "C"), each=3) 
Stats <- rep(c("Mean", "Median", "InGroupVar"), 3) 
paste(Names, Stats, sep="_") 
[1] "A_Mean"  "A_Median"  "A_InGroupVar" "B_Mean"  "B_Median"  
[6] "B_InGroupVar" "C_Mean"  "C_Median"  "C_InGroupVar" 
+0

謝謝,這正是我以後的!似乎很明顯現在 – LoveMeow 2014-08-28 03:26:13

+1

你也可以做到這一點,而不必再次調用'rep'。 'paste0(Names,「_」,c(「Mean」,「Median」,「InGroupVar」))' – 2014-08-28 04:57:56

+0

當然,但我故意選擇了顯示使用'rep'的不同方式。但是謝謝你的貢獻。 – 2014-08-28 04:59:58

3

我喜歡sprintf更好地爲這個特殊的問題:

Names <- c("A", "B", "C") 

sprintf("%s_%s", 
     rep(Names, each = 3), 
     c("Mean", "Median", "InGroupVar")) 
# [1] "A_Mean"  "A_Median"  "A_InGroupVar" "B_Mean"  
# [5] "B_Median"  "B_InGroupVar" "C_Mean"  "C_Median"  
# [9] "C_InGroupVar" 

另外,這也適用,但給你以不同的順序結果:

do.call(paste, 
     c(expand.grid(
      Names, c("Mean", "Median", "InGroupVar")), 
      sep = "_")) 
# [1] "A_Mean"  "B_Mean"  "C_Mean"  "A_Median"  
# [5] "B_Median"  "C_Median"  "A_InGroupVar" "B_InGroupVar" 
# [9] "C_InGroupVar" 
相關問題