【问题标题】:Use of return() in tidy style when creating functions with dbplyr使用 dbplyr 创建函数时以整洁的方式使用 return()
【发布时间】:2017-09-08 15:55:50
【问题描述】:

我试图弄清楚如何将tidy style guide 应用于我正在创建的一些函数。具体来说,我试图限制我对return() 的使用——根据风格指南的建议,仅在提前退货的情况下使用——在dbplyr 函数的上下文中。在阅读风格指南之前,我会这样做(你需要 dplyrdbplyr 来运行它):

cars_return <- function(){
  con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
  dplyr::copy_to(con, mtcars)

  mtcars2 <- dplyr::tbl(con, "mtcars")

  mtcars2 <- dplyr::collect(mtcars2)

  return(mtcars2)

  DBI::dbDisconnect(con)
}

哪个会返回这个:

> cars_return()
# A tibble: 32 x 11
     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1  21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4
 2  21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4
 3  22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1
 4  21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1
 5  18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2
 6  18.1     6 225.0   105  2.76 3.460 20.22     1     0     3     1
 7  14.3     8 360.0   245  3.21 3.570 15.84     0     0     3     4
 8  24.4     4 146.7    62  3.69 3.190 20.00     1     0     4     2
 9  22.8     4 140.8    95  3.92 3.150 22.90     1     0     4     2
10  19.2     6 167.6   123  3.92 3.440 18.30     1     0     4     4
# ... with 22 more rows

但是,如果我尝试像这样省略 return()

cars_no_return <- function(){
  con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
  dplyr::copy_to(con, mtcars)

  mtcars2 <- dplyr::tbl(con, "mtcars")

  dplyr::collect(mtcars2)

  DBI::dbDisconnect(con)
}

然后当我调用该函数时,我什么也没返回:

> cars_no_return()
>

所以我的问题是,我如何处理需要使用collect() 从数据库返回data.frame 的函数,同时尊重tidy style guide

【问题讨论】:

  • 在返回的第一种情况下,从未运行过断开连接,因为它出现在返回之后。如果您想关闭这样的连接,请查看?on.exit 函数的帮助

标签: r dplyr tidyverse dbplyr


【解决方案1】:

您应该查看on.exit。例如见How and when should I use on.exit?

cars_return <- function(){
  con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")

  on.exit(DBI::dbDisconnect(con))

  dplyr::copy_to(con, mtcars)

  mtcars2 <- dplyr::tbl(con, "mtcars")

  mtcars2 <- dplyr::collect(mtcars2)

  mtcars2
}

【讨论】:

  • 好的,这非常有用。完全有道理。你能解释一下为什么mtcars2return(mtcars2) 更可取吗?
  • 很高兴它有帮助。 return() 实际上并没有什么不同。我只是没有使用它,因为它符合tidyverse style guide,因为您不再试图提前返回某些东西,而不是您正在使用on.exit
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多