Aure
Aure

Reputation: 3

How to use the counter in a for loop as a number to define a new array

To make it simple: How can i change this expression?

for (i in 1:5){ai=i}

in a way that in "ai" the i is interpreted as a counter and not as a letter "i", so that it creates

a1=1, a2=2,...

I remember a language where you could just use $i to solve this

for (i in 1:5){a$i=i}

but i didn't find the equivalent in R, can someone help me ??

Upvotes: 0

Views: 71

Answers (3)

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

You can use assign

for (i in 1:5) 
  assign(paste0("a", i), i)

but I do not recommend this approach. You can use a vector or a list instead:

a <- list()
for (i in 1:5)
  a <- append(a, i)

Upvotes: 1

Andriy T.
Andriy T.

Reputation: 2030

Try:

a <- NULL
for (i in 1:5) a[i] <- i

Upvotes: 0

liall
liall

Reputation: 1

in C++ it is done as:

a[i] = i;

where a[i] signifies i+1th element in array

Upvotes: 0

Related Questions