Search code examples
rindirect-objects

How to use indirect reference to read contents into a data table in R.


How do you use indirect references in R? More specifically, in the following simple read statement, I would like to be able to use a variable name to read inputFile into data table myTable.

myTable <- read.csv(inputFile, sep=",", header=T)

Instead of the above, I want to define

refToMyTable <- "myTable"

Then, how can I use refToMyTable instead of myTable to read inputFile into myTable?

Thanks for the help.


Solution

  • R doesn't really have references like that, but you can use strings to retrieve/create variables of that name.

    But first let me say this is generally not a good practice. If you're looking to do this type of thing, it's generally a sign that you're not doing it "the R way.'

    Nevertheless

    assign(refToMyTable, read.csv(inputFile, sep=",", header=T))
    

    Should to the trick. And the complement to assign is get to retrieve a variable's value using it's name.