Search code examples
rfor-loopcreate-tablevariable-names

Create and use different tables in for-loops in R in a shorter way


I’m looking for a short solution to create and use different tables in for loops where the loop variable is part of the name.

I found the following solutions:

If I want to create tables in a loop I may use assign together with paste. E.g.:

for (f in files){
assign(paste0("A_",f), readWorksheetFromFile(paste0(f,".xlsx")))}

And if I want to use these tables I may use eval, parse and paste0 in the following way:

for(f in files){
  x <- eval(parse(text=paste0("A_",f)))}

The problem is that I have to use these constructions very often and the code is getting very long. Does anyone has a shorter solution to do this in R?

E.g. in SAS I could use something like (as I remember)

x = A_&f;

instead of

x <- eval(parse(text=paste0("A_",f)))

Edit

Based on the following answers I found this solution:

In the process of creating objects in a loop I may use the function

`%c%` = function(a, b) paste0(a, b) 

in the following way for two or more strings:

"A_" %c% f 
"A_" %c% f %c% r

In case I want to use this object in a loop I can use the function:

`%u%` = function(a, b) eval(parse(text=paste0(a,b))) 

in the following way for two or more strings:

"A_" %u% f
"A_" %c% f %u% r

Notice that I used the %u% only in the last step.


Solution

  • You could try using a list:

    l = vector("list", length(files))
    names(l) = paste0("A_", files)
    for(i in seq_along(files))
      l[[i]] = readWorksheetFromFile(paste0(files[i],".xlsx")))
    

    If you need them to be separate variables, you could create your own environment and store them there:

    myenv = new.env()
    lapply(seq_along(l), function(i) assign(names(l)[i], l[[i]], pos = myenv))
    

    And retrieve the variables using get:

    vars = ls(pos = myenv)
    get(vars[1], pos = myenv) 
    

    EDIT

    So really you're just looking for an operator like _&:

    `%&%` = function(a, b) get(paste0(a, "_", b))
    
    "A" %&% f
    
    A = "A"
    A %&% f