简体   繁体   中英

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.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM