-1

I know it is bad practice and i know it is easier with a list. But just of interest.

I have variables a1, a2, a3, ..., a"n"

Is something like this possible:

for i in (1:n)
{
  a"i" <- i
}

Thanks for your reply!

Triss
  • 561
  • 3
  • 11
  • Yes, it is. See `help("assign")` and if you still have doubts say so. – Rui Barradas Sep 17 '18 at 13:50
  • 2
    `a <- 1:n` For more complex situation use `a <- sapply(1:n, ...)` Please do **not** use `assign()` https://stackoverflow.com/questions/17559390/why-is-using-assign-bad?s=1|84.6357 and `library("fortunes"); fortune(236)` – jogo Sep 17 '18 at 13:50
  • Thank you for your answer.I know the assign command. The problem is, is it possible if the variables already exist? – Triss Sep 17 '18 at 13:51
  • If one of the variables, e.g. `a5`, already exists it is overwritten by using `assign("a5", ...)`. Therefore it is bad to generate a mass of variables. It is bette to use a list which can hold a lot of elements. – jogo Sep 17 '18 at 14:30
  • Hiho Triss, welcome to stackoverflow. Why not using a list with length n instead of n single variables named a1 toll an? This way you can add the current value to the list on position [i] – TinglTanglBob Sep 17 '18 at 14:37
  • @Triss From your comment to an answer is clear that the question misses essential information about the generated objects and the desired structure of the result. Please put more code and information in your question, i.e. edit your question: https://stackoverflow.com/posts/52369297/edit Give a [mcve] and read https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – jogo Sep 17 '18 at 17:22

1 Answers1

1

Yes,

assign(paste('a', i, sep=''), 'hello')

Should do the trick. And yes, it works even if the variable already exists.

get(paste('a', i, sep=''))

Gives you the value of the variable a1.

compuTE
  • 120
  • 1
  • 10
  • 2
    https://stackoverflow.com/questions/17559390/why-is-using-assign-bad?s=1|84.6357 and `library("fortunes"); fortune(236)` – jogo Sep 17 '18 at 13:58
  • Thank you, but now a1, a2 and so on are matrices and i only want to change the first row in the existing matrix and not create a new one with 'paste'. With `get(paste('a',i,sep=''))` i get the first row, but i cant change it separately? For example: `assign(paste('a', 1, sep=''),matrix(0,4,2)) get(paste('a',1,sep=''))[1,]` but `get(paste('a',1,sep=''))[1,]<-c(1,2)` isnt possible – Triss Sep 17 '18 at 15:01
  • 1
    @Triss The example you use in your question doesn't make any reference to matrices or partial row/column assignment. It would have been good to include that. You can't use the `[<-` operator with get/assign. You'd need to do the `get()`, do the `[<-` to the value returned by get. And then use that new value in the `assign()`. This is yet another reason that `get/assign` should be avoided -- they do not work with the row/column assignment operator. – MrFlick Sep 17 '18 at 16:35