-1

I seem to remember there was a function I could call on a dataframe that allowed for the columns to be called as a global object. similar to typing DF$var. Does anyone know what I'm talking bout or am I imagining things?

I'm not sure if this was a function or a IDE feature.

Phil
  • 7,287
  • 3
  • 36
  • 66

3 Answers3

1

You can use list2env

list2env(mtcars, .GlobalEnv)

mpg
# [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8
#[12] 16.4 17.3 15.2 10.4 10.4 14.7 32.4 30.4 33.9 21.5 15.5
#[23] 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7 15.0 21.4
cyl
# [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4
#[29] 8 6 8 4
am
# [1] 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1
#[29] 1 1 1 1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

OOH I think I found it! attach() and detach() it allows you to... "Assign a value to a name in an environment."

so if you do assign(DF) then you can call any column that was in DF by name and Rstudio will auto complete when you're typing for a bonus.

detach(DF) will do the opposite.

  • 1
    Be very careful using `attach()`/`detach()`. It is very easy to forget to apply the latter, and you can run into some very odd behaviour because of that. Also, it's generally disliked because it actually takes away from one of the core strengths of R (in relation to, say, SPSS) which is that you can handle multiple data frames in the same environment. All in all, I would recommend to never use it. – Phil Dec 06 '20 at 07:25
  • I have had issues in the past with forgetting to detach but I hadn't heard the other criticism. someone else recommended list2env(), does it somehow avoid those pitfalls or is it the same issue? – Jason Deutsch Dec 06 '20 at 07:32
  • 1
    It can still lead to confusion. Let's say that you are working on a relational set of data frames, and there's an id variable that is the link to several data frames. If you apply `attach()` or `list2env` and you call the id variable, it can be very easy to forget which data frame you are referring to. More discussion can be found here https://stackoverflow.com/questions/10067680/why-is-it-not-advisable-to-use-attach-in-r-and-what-should-i-use-instead – Phil Dec 06 '20 at 07:49
  • `attach` is not recommended. It puts the data frame on the search path and then if you modify it you get a second version masking the first leading to confusion. Use `with`, `transform`, `subset`, `aggregate` and others instead. Carefully read `?attach` and also check out this video: https://www.youtube.com/watch?v=SW_TUkPXSmA – G. Grothendieck Dec 06 '20 at 14:30
0

We could use assign

for(nm in names(mtcars)) assign(nm, mtcars[[nm]])
akrun
  • 874,273
  • 37
  • 540
  • 662