2011-06-23 10 views
6

Używam R. Załóżmy, że mam wektor miast i chcę używać tych nazw miast pojedynczo w ciągu znaków.Przypisywanie różnych wartości do elementu w ciągu znaków

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

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

Więc chcę skończyć z czterema oddzielnymi zwrotami.

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

Czy istnieje funkcja podobna do formatu() w Pythonie, który pozwoli mi wykonać to zadanie w prosty/efektywny sposób?

Chciałbym uniknąć czegoś takiego jak poniżej.

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

Odpowiedz

14

Co powiecie na 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 nie wiedział o sprintf() Dzięki! – ATMathew

+0

Nie ma printf, ale możesz przetasować własny z 'printf <- function (format_string, ...) {cat (sprintf (format_string, ...))} – Zach

7

zależności od tego, jak skomplikowany musi być prosta pasta mógł wykonać zadanie:

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

robi to, co chcesz.

@ odpowiedź Zacha, sprintf ma wiele zalet, choć, jak prawidłowego formatowania deblu itp

Powiązane problemy