-1

I'm sure there is an easy answer. I have a loop, where for each iteration, I create a new vector to store the results. I do this by pasting a name together and then assigning that name to an empty vector.

for (i in seq(1, 50)) {

    current_iteration = i

    x = paste0("resultsVec", current_iteration)

    assign(x, rep(NA, 43))

    paste0("resultsVec", i)

    for (j in seq(1, 100))
    {
        resultsVeci[j] = j * j # <- problem here 
    }


}

However, you obviously can't refer to 'resultsVeci' - so how to I refer to the iteration specific vector each loop?

If you do paste0("resultsVec", i), where i=2 for example, it returns a string "resultsVec2", rather than the object resultsVec2. How do I refer to the object rather than the string?

Thanks.

user438383
  • 5,716
  • 8
  • 28
  • 43

1 Answers1

2

It really isn't a good idea to use get() and assign() with most R code. (Why is using assign bad?). Better to just use a list. A simple lapply would work here.

resultsVec<-lapply(1:50, function(i) (1:100)*(1:100))

and then you can get the values with reusltsVec[[1]], resultsVec[[2]], etc

MrFlick
  • 195,160
  • 17
  • 277
  • 295