0

Let's say that I have a data frame that looks like the following.

dt = data.frame(a = rnorm(5), b = rnorm(5))

I would like to assign a set of column variables as a vector.

colvec <- c("a","b")

So for these two columns in the vector, I'd like to dynamically take that column and create a vector of the same name.

So the normal way to do this would be to do...

a = dt$a

b = dt$b

But I want to do this dynamically. Any suggestions?

  • 1
    Don't do that. At best, this will make everything that follows more difficult. – Roland Aug 02 '21 at 10:36
  • @Roland would you mind elaborating on this? – tmfmnk Aug 02 '21 at 10:40
  • 2
    @tmfmnk If you want to create these vectors with dynamic names, the logical next steps include referencing them programmatically. That leads to very cumbersome `get`/`assign` constructions. And, it's totally not necessary. Referencing data.frame columns, even iterating over data.frame columns is much easier. Or, alternatively, you could just use fixed instead of dynamic names. There is no valid reason to create vectors in the global environment with dynamic names. – Roland Aug 02 '21 at 10:47
  • @Roland I totally agree with you. I was just curious whether there are reasons that I'm not aware of. – tmfmnk Aug 02 '21 at 10:50

1 Answers1

2

Not sure if this is a good idea, but you can do:

sapply(colvec, function(x) assign(x, dt[, x], envir = .GlobalEnv))
Martin Gal
  • 16,640
  • 5
  • 21
  • 39