bird
bird

Reputation: 3294

How to assign a variable name in a loop in R

imagine I want to go through a loop and when I find the value that I am interested in, I want to use that value as a new variable name. The code below can better describe what I mean.

Here I want the name Bob to be a new variable containing the character value "my_name". But this code that I have written does not do the job. I would greatly appreciate if someone points out where I make the mistake

names = c("Tom", "Bob", "Dan")
for (i in 1:length(names)){
    name = names[i]
    if (names[i] == "Bob"){
            names[i] = "my_name"
            print(Bob)
        }
}

Upvotes: 2

Views: 1519

Answers (1)

tacoman
tacoman

Reputation: 947

you can make use of "assign".

names = c("Tom", "Bob", "Dan")
for (i in 1:length(names)){
    name = names[i]
    if (names[i] == "Bob"){
            assign(names[i],"my_name")
            print(Bob)
        }
}

Upvotes: 4

Related Questions