Mislav
Mislav

Reputation: 1563

Using dplyr::tbl inside function

I now there are various answers on using dplyr inside function but i tried all methods and neither worked.

Here is my simple function:

loadData_gfi_zse <- function(table_name = "mytable_name"){
  con <- DBI::dbConnect(RMySQL::MySQL(), 
                        host = "xxxx",
                        user = "xxxx",
                        password = "xxxx",
                        dbname = "xxxxs")
  table_name <- substitute(table_name)
  df <- tbl(con, lazyeval::interp(table_name))
  dbDisconnect(con)
  df_clean
}

I tried wit rlang::!! and other methods but neither work. This should be straightforward, but I can't get it work.

Upvotes: 1

Views: 555

Answers (1)

Aur&#232;le
Aur&#232;le

Reputation: 12839

library(dplyr)

con <- DBI::dbConnect(RSQLite::SQLite(), dbname = "dummydb.sqlite")
DBI::dbWriteTable(con, "iris", head(iris))
DBI::dbDisconnect(con)

loadData_gfi_zse <- function(table_name = "mytable_name") {
  con <- DBI::dbConnect(RSQLite::SQLite(), dbname = "dummydb.sqlite")
  on.exit(DBI::dbDisconnect(con))
  collect(tbl(con, table_name))
}

loadData_gfi_zse(table_name = "iris")

# # A tibble: 6 x 5
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#          <dbl>       <dbl>        <dbl>       <dbl> <chr>  
# 1          5.1         3.5          1.4         0.2 setosa 
# 2          4.9         3            1.4         0.2 setosa 
# 3          4.7         3.2          1.3         0.2 setosa 
# 4          4.6         3.1          1.5         0.2 setosa 
# 5          5           3.6          1.4         0.2 setosa 
# 6          5.4         3.9          1.7         0.4 setosa 

unlink("dummydb.sqlite")

Upvotes: 2

Related Questions