0

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

I_O
  • 4,983
  • 2
  • 2
  • 15
user34561
  • 9
  • 1
  • 1
    Technically that's possible: `for(i in 1:5) assign(paste0('b', i), 5)`. Note that your environment ("workplace") might soon become a mess of objects - which might better be collected and managed as lists, dataframes ... – I_O Dec 11 '22 at 10:54

2 Answers2

0

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?

user12256545
  • 2,755
  • 4
  • 14
  • 28
-1

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