3

Imagine we have:

X <- 1:4
names(X) <- c("A" ,"B" , "C", "D")

I would like to create four objects in the global environment, A, B, C, D, each with the corresponding values 1, 2, 3, 4. I assume the solution involves the assign and apply functions but hope someone here could come up with something nicer than I could.

(Context: I'd like to create a kind of pseudo make file, based around a named character vector in which the names are the names of the objects I'd like to create, and the values are the names and locations of csv files I'd like to populate each object with... The toy example above is a step towards this.)

JonMinton
  • 1,239
  • 2
  • 8
  • 26
  • 2
    Better put everything in a list. Some version of [this](http://stackoverflow.com/a/11433532/1412059) should be a better alternative. – Roland Jun 28 '14 at 09:22
  • Thanks. I agree in general about lists but think this might be an exception. I want to create a semi makefile script that will fetch and prepare a number of dataframes for further analysis, but of course I won't know exactly how many datasets will be used in the end, so don't want the names and number of dataframes to be hardcoded at the start. – JonMinton Jun 28 '14 at 09:33
  • Well, usually you put all files in one directory and then use `lapply` with `list.files` and `read.csv`. I don't see how your use case is an exception. – Roland Jun 28 '14 at 10:14

2 Answers2

3

You can use list2env :

list2env(as.list(X),.GlobalEnv)

Of course as mentioned in the comment, it is not a good practice to use separated global variables and clutter the global environment . The R way , is to keep your variables in a list or a vector and use xxapply family functions to manipulate each vector element.

agstudy
  • 119,832
  • 17
  • 199
  • 261
3

Try like this:

for(i in seq_along(x)){
     assign(names(x)[i],x[i])
}
bartektartanus
  • 15,284
  • 6
  • 74
  • 102