Eric Wang
Eric Wang

Reputation: 83

R loop change variable names

Looked over several posts on this topic, but still couldn't figure out. Thought I'd just ask:

I wrote a for-loop:

for (i in 0:5) {
     est16_y2016$pov50_[i] <- est16_y2016$pop[i]*est16_y2016$ITPR_0.5
               }

to achieve the same results as the following code:

 est16_y2016$pov50_0 <- est16_y2016$pop0 * est16_y2016$ITPR_0.5
 est16_y2016$pov50_1 <- est16_y2016$pop1 * est16_y2016$ITPR_0.5
 est16_y2016$pov50_2 <- est16_y2016$pop2 * est16_y2016$ITPR_0.5 
 est16_y2016$pov50_3 <- est16_y2016$pop3 * est16_y2016$ITPR_0.5 
 est16_y2016$pov50_4 <- est16_y2016$pop4 * est16_y2016$ITPR_0.5 
 est16_y2016$pov50_5 <- est16_y2016$pop5 * est16_y2016$ITPR_0.5 

But the loop doesn't work. No error message, no new variables generated either. Help! Thanks.

Upvotes: 1

Views: 12608

Answers (3)

FewKey
FewKey

Reputation: 191

It is easy to create a new variable name with paste(), and the problem is how to use the corresponding variable instead of the name of a variable.

  for (i in 0:5){ 
    # Create new variable names
    pov.name = paste0("est16_y2016$pov50_",i)
    pop.name = paste0("est16_y2016$pop",i)

    assign(pov.name,eval(parse(text = pop.name))*est16_y2016$ITPR_0.5)
    }

In this code,

eval(parse(text = pop.name) uses the string "pop.name" as a variable name

assign(pov.name,value1)creates a variable named pov.name and assigns value1 to pov.name

This way, you can get six new variables without using a dataframe.

Upvotes: -1

GordonShumway
GordonShumway

Reputation: 2056

It's kind of hard to answer your question without a reproducible example but I will give it a shot. est16_y2016$pop[i] will give you the ith element of est16_y2016$pop (which probably doesn't even exist. What you want instead is est16_y2016[paste0("pop",i)] so you code should look like this:

for (i in 0:5) 
    {
     est16_y2016[[paste0("pov50_",i)]] <- est16_y2016[[paste0("pop",i)]]*est16_y2016$ITPR_0.5
     }

(edited)

Upvotes: 0

Rui Barradas
Rui Barradas

Reputation: 76402

Though the construct data$column_name is very convenient when in an interactive R session, when programming it may cause some problems. @A.Suliman's comment presents a way to solve those problems, here is another one.

for(i in 0:5){
    target <- paste("pov50", i, sep = "_")
    pop <- paste0("pop",i)
    est16_y2016[[target]] <- est16_y2016[[pop]]*est16_y2016[["ITPR_0.5"]]
}

Upvotes: 3

Related Questions