2

I want to rename an existing data frame to the name in a variable. Any ideas are appreciated.

rtbl <- load("clarktestjunk.RData")

datasetname = "specialdata" # passed in by the user
rename(rtbl,datasetname) # this is not the correct command

specialdata # this is how I want to reference the data set down stream.
Jaap
  • 81,064
  • 34
  • 182
  • 193
Clark E Flowers
  • 21
  • 1
  • 1
  • 2
  • Related posts: http://stackoverflow.com/questions/22951811, http://stackoverflow.com/questions/2717757 – zx8754 Mar 07 '16 at 18:53
  • I figured it out. eval(parse(text=paste(datasetname,"<-rtbl"))) – Clark E Flowers Mar 07 '16 at 22:55
  • "If the answer is parse() you should usually rethink the question." -- Thomas Lumley R-help (February 2005). Also, see [What specifically are the dangers of eval(parse(…))?](http://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse) – zx8754 Mar 08 '16 at 07:19

2 Answers2

2

An object can't be renamed in the way your pseudo-code implies. You can assign the contents of the the data.frame to a new object with a known name. (See @Wave's solution with assign.) But the original object will still exist.

rm(list=ls())
data(cars)
ls()
# [1] "cars"
assign("renamed_cars", cars)
ls()
# [1] "cars"         "renamed_cars"
rm(cars)
ls()
# [1] "renamed_cars"
effel
  • 1,421
  • 1
  • 9
  • 17
1

This is a way (which works not only for data frames):

old.name=data.frame(a=1:5,b=6:10)
assign("new.name",old.name)

> new.name
  a  b
1 1  6
2 2  7
3 3  8
4 4  9
5 5 10
Wave
  • 1,216
  • 1
  • 9
  • 22