Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning different values to an element in a string

Tags:

string

r

I'm using R. Let's say I have a vector of cities and I want to use those city names individually in a string.

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

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

So I want to end up with four seperate phrases.

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

Is there a function similar to format() in Python which will allow me to perform this task in a simple/efficient manner?

Would like to avoid something like below.

for( i in city){
    phrase = c("Hey ", i, "what's the meaning of life?")
}
like image 793
ATMathew Avatar asked Jun 23 '11 18:06

ATMathew


People also ask

How do you assign a value to a string variable?

String objects are immutable - you cannot change their value - while doing assignments you are changing object to which the variable (or variable at given array index) is referring to. String[] fields = {firstNameField, lastNameField, firstName, lastName};

Can we assign value to string?

You can't assign strings. But you can call functions to help achieve what you want.

How do you assign a value to a string in Python?

To assign it to a variable, we can use the variable name and “=” operator. Normally single and double quotes are used to assign a string with a single line of character but triple quotes are used to assign a string with multi-lines of character. This is how to declare and assign a variable to a string in Python.


1 Answers

How about 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?"   
like image 166
Zach Avatar answered Oct 19 '22 23:10

Zach