0

I already know that if I assign variable in for loop, I should use assign() like this

for(i in 1:6) { #-- Create objects  'r.1', 'r.2', ... 'r.6' --
   nam <- paste("r", i, sep = ".")
   assign(nam, 1:i)
}

But I wonder what fundamentally difference is between <- and assign()

I read documentation, and I know that assign() access the environment.

It is the only difference I know.

Ronak Shah
  • 286,338
  • 16
  • 97
  • 143
0 Hong
  • 313
  • 1
  • 8
  • 11
    Ideally you should avoid using `assign`. Read more [here](https://stackoverflow.com/questions/17559390/why-is-using-assign-bad). – Ronak Shah Aug 02 '18 at 01:28
  • 11
    The only good time to use `assign` is when you're doing things you shouldn't be doing. Take your example ... you should be using a named list for that. – Rich Scriven Aug 02 '18 at 01:32
  • I read that. For data analysis(like `lm()`) and FP, I had better make named list, not multiple variable right? – 0 Hong Aug 02 '18 at 02:10
  • For things like `lm`, structures like `data.frame` exist for precisely this purpose – MichaelChirico Aug 02 '18 at 02:41
  • 4
    Don't use assign. Don't make objects `r.1`, `r.2`, `r.3`, ... make a list named `r` and you can use `r[[1]]`, `r[[2]]`, `r[[3]]`, `r[[some_variable]]`. You can assign names to the list or use indices. In addition to Ronak's link, I'd recommend [How to make a list of data frames](https://stackoverflow.com/a/24376207/903061) for the discussion of why sequentially named variables are hard to work with and how `list`s are a great alternative. – Gregor Thomas Aug 02 '18 at 03:23
  • As for the difference, try doing what you're doing without `assign` and see that it doesn't work. If you do `nam – Gregor Thomas Aug 02 '18 at 03:24
  • 2
    `fortunes::fortune(236)`: *The only people who should use the assign function are those who fully understand why you should never use the assign function.* -- Greg Snow R-help (July 2009) – Uwe Aug 02 '18 at 05:52
  • 2
    The "only difference [you] know" is actually a very important difference. `assign` gives you precise control where you assign into. That can be important for some advanced stuff. As a beginner, you don't need `assign` and shouldn't use it. – Roland Aug 02 '18 at 06:00

0 Answers0