Home > Net >  How to change the number of a value in a for loop
How to change the number of a value in a for loop

Time:12-11

my question is quite simple.

I would like to change the ending name of a variable in a for loop according to i. I know I have used this somewhere, but I can't find it anywhere. Does anyone have any ideas?

For example:

for (i in 1:5){ paste0("b",i) = 5 }

---> I would like to get: b1 = 5 b2 = 5 ... b5 = 5

CodePudding user response:

You can't change the number of iterations of a for loop while it is running.The input N is evaluated prior to running of the for loop. You can , however use for loop with a conditional stop terminal and have code inside the loop determine whether or not to continue

CodePudding user response:

Welcome to SO!, If you are talking about a named vector, you can reassign the name using the name() function. The example is using a for loop and gsub to replace the number 1 (by using regular expression \\d : anynumber) with the position i in the vector (ie 1,2,3,4,5) .

> v <- c(1:5)  ; names(v)<- paste0(LETTERS[1:5],1)
> v
A1 B1 C1 D1 E1 
 1  2  3  4  5 
> for (i in 1:length(v)) {
    names(v)[i]<-gsub("\\d",i,names(v)[i])
  }
> v
A1 B2 C3 D4 E5 
 1  2  3  4  5 

Is this what you are looking for?

  • Related