Home > Mobile >  How to assign to a data.table a variable name received as parameter in a function
How to assign to a data.table a variable name received as parameter in a function

Time:09-30

I need have a data.table named "clients", the name is same that is in my database. (this example is with table "clients" but i will need more tables with others names)

tbl_import <- function (table)
{
        sql<-glue_sql(paste0("select * from table"),.con=con)
    
    table <- dbGetQuery(con,sql)
    setDT(table)
      
    table <<- copy(table)
        table <<- table ##I replace with this too in another try but didn't work either
}
tbl_import("clients")

When i run this i don't have the data.table with the name of "clients",I get a table with name "table"

CodePudding user response:

Use assign() to create a variable with a custom name (table_name) in the caller environment (parent.frame()

tbl_import <- function (table_name) {
  sql <- glue_sql("select * from {`table_name`}",.con=con)
  x <- dbGetQuery(con,sql)
  assign(table_name, setDT(x), parent.frame())
}
tbl_import("clients")

CodePudding user response:

Just assign the function to a new name.

clients <- tbl_import("clients")
  • Related