[R] Assign Name of Data Frame

Marc Schwartz marc_schwartz at me.com
Fri Feb 12 17:00:43 CET 2010


On Feb 12, 2010, at 8:19 AM, mah wrote:

> Hello R Experts,
> 
> How can I assign the name of a data frame with the argument of a
> function?  Specifically I am using RODBC to build local dataframes
> from SAS datasets on a
> remote server.  I would like the local dataframe have the same name as
> the source SAS dataset, and the function below is what I am
> developing.  However, the "substitute(table)" on the left side of the
> assignment
> generates the error "Error in substitute(table) <<- sqlQuery(sears,
> sql.stmt) :
> could not find function "substitute<-".
> 
> Thanks in advance
> 
> MakeDF <- function(table)
> #------------------------------------------------------------
> # Function makes dataframe from UNIX SAS datasets
> #------------------------------------------------------------
> {
> st.time <- Sys.time()
> print(substitute(table))
> sql.stmt <- paste("select * from swprod.", substitute(table),
> sep="")
> print(sql.stmt)
> substitute(table) <<- sqlQuery(sears, sql.stmt)
> #  deparse(substitute(table)) <<- sqlQuery(sears, sql.stmt)
> end.time
> print(end.time - st.time)
> }
> MakeDF(sku_series)



My recommendation would be something like this:

MakeDF <- function(table)
{
  DF <- sqlQuery(channel, paste("select * from swprod.", table, sep = ""))
  assign(table, DF, envir = parent.frame())
}

Then use would be:

  MakeDF("sku_series")


The result would be a data frame called 'sku_series' in the calling environment.  You could substitute globalenv() for parent.frame() if you wanted to create the data frame in the global environment.

See ?assign

HTH,

Marc Schwartz



More information about the R-help mailing list