为字符串中的元素指定不同的值

时间:2011-06-23 18:00:25

标签: string r

我正在使用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中是否有类似于format()的函数允许 我能以简单/有效的方式完成这项任务吗?

想避免下面的事情。

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

2 个答案:

答案 0 :(得分: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?"   

答案 1 :(得分:7)

根据需要的复杂程度,一个简单的粘贴可以完成这项工作:

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

做你想做的事。

@Zach的答案,sprintf虽然有很多优点,比如正确格式化双打等。