Reputation: 3
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.
Upvotes: 0
Views: 3651
Reputation: 263411
Perhaps assign
as mentioned by MrFlick.
When you want the contents of the object named "myTable" you would use get
:
get("myTable")
get(refToMyTable) # since get will evaluate its argument
(It would be better to assign results of multiple such dataframes to a ist object or a Reference Class.)
If you wanted a language-name object you would use as.name
:
as.name("myTable")
# myTable .... is printed at the console; note no quotes
str(as.name("myTable"))
#symbol myTable
Upvotes: 1
Reputation: 206401
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.
Upvotes: 1
Reputation: 47
I think you mean something like the following:
reftomytable='~/Documents/myfile.csv'
myTable=read.csv(reftomytable)
Upvotes: 0