Flo Chi
Flo Chi

Reputation: 65

Create a new vector every loop iteration in R

I have the following problem: I have a for-loop => for (i in 1:20){t <- c(t,print(i:20))} ...

I know how to save all the results in one vector, but I want to save the results of EACH iteration as an own vector (like you see it above) => so that e.g. t[18] is just 18 19 20 and t[20] is just 20 I thought about a matrix as well, but each row must end with "20" so the rest needs to be filled up with "0" in a 20x20 matrix ...

Upvotes: 1

Views: 3075

Answers (3)

Nikos
Nikos

Reputation: 3297

I would adjust @beginneR's answer like this:

lst <-vector("list",20)
for (i in 1:20){
  lst[[i]] <- i:20
}

It is only a small addition but if makes a big difference in performance terms if you increase the size of the list (e.g millions).

Upvotes: 1

Romain
Romain

Reputation: 859

I strongly agree with @beginneR, however if you really want new variables in the loop you can use assign().

for (i in 1:20){
  assign(paste("t",i, sep = ""), i:20)
}

This will give you the variable t1, t2 etc. as you want them. Again I strongly advise to use a list this kind of approach is hardly scalable.

Upvotes: 0

talat
talat

Reputation: 70256

How about a list for that purpose:

lst <- list()

for (i in 1:20){
  lst[[i]] <- i:20
}

Then acces it by calling e.g.

lst[[18]]
#[1] 18 19 20

Upvotes: 1

Related Questions