2011-06-23 49 views
6

我使用的是R. 假設我有一個城市矢量,我想在字符串中單獨使用這些城市名稱 。爲字符串中的元素指定不同的值

city = c("Dallas", "Houston", "El Paso", "Waco") 

phrase = c("Hey {city}, what's the meaning of life?") 

所以我想結束四個單獨的短語。

"Hey Dallas, what's the meaning of life?" 
"Hey Houston, what's the meaning of life?" 
... 

是否有一個功能類似Python的格式(),這將使 我在一個簡單/高效的方式執行這項任務?

想避免像下面這樣的東西。

for(i in city){ 
    phrase = c("Hey ", i, "what's the meaning of life?") 
} 

回答

14

sprintf怎麼樣?

> city = c("Dallas", "Houston", "El Paso", "Waco") 
> phrase = c("Hey %s, what's the meaning of life?") 
> sprintf(phrase, city) 
[1] "Hey Dallas, what's the meaning of life?" "Hey Houston, what's the meaning of life?" 
[3] "Hey El Paso, what's the meaning of life?" "Hey Waco, what's the meaning of life?" 
+0

+1從來不知道的sprintf()謝謝! – ATMathew

+0

沒有printf,但是你可以用'printf < - function(format_string,...){cat(sprintf(format_string,...))} – Zach

7

取決於它需要多麼複雜是,一個簡單的粘貼可以做的工作:

paste("Hey ", city, ", what's the meaning of life", sep="") 

你想要做什麼。

@扎克的回答,sprintf的有很多的優點,雖然一樣,雙打等的正確的格式

相關問題