2

我目前正在使用以下内容使用 dbplyr 提取数据集:

connectInfo <- dbConnect(
  odbc(),
  Driver = "SQL Server",
  Server = "myServerName",
  Database = "myDatabaseName",
  Trusted_Connection = "True"
)

tbl(connectInfo, "tableName") %>%
  summarise(
    nbDate = LEFT(nbDate, 5),
    book,
    rateFeeChg
  ) %>%
  mutate(
    rateFeeChg = rateFeeChg * 100
  )

使用以下输出:

   nbDate    book rateFeeChg
    <chr>   <chr>      <dbl>
 1  38348 Classic  0.0000000
 2  38744 Classic  2.1270990
 3  39640 Classic  2.8999999
 4  40423 Classic  0.0000000
# ... with more rows

我想要做的是将这些 5 位日期值转换为 mutate 函数内的常规日期值。我知道通过使用看门人库我可以轻松地转换它,但是当我尝试把

mutate(
    rateFeeChg = rateFeeChg * 100,
    nbDate = janitor::excel_numeric_to_date(nbDate)
)

我收到以下错误:

Error in janitor::excel_numeric_to_date(nbDate) : 
  object 'nbDate' not found
4

1 回答 1

2

主要的是,在 MS SQL 中,这种转换首先需要进入datetime,然后进入date。由于dbplyr目前没有强制进入的函数datetime,所以最好的办法是使用sql()传递 MS SQL 命令。这样,您可以保留所有进程服务器端,并避免collect()将数据放入 R 内存中。SQL 中的默认datetime转换似乎与 Excel 具有相同的基准日期,因此您应该得到相同的日期。这是我刚刚在我的系统上测试过的建议解决方案:

tbl(connectInfo, "tableName") %>%
   summarise(
   nbDate = sql("CAST(LEFT(nbDate, 5) as datetime)"),
   book,
   rateFeeChg
 ) %>%
 mutate(
  nbDate = as.Date(nbDate),
  rateFeeChg = rateFeeChg * 100
 )
于 2018-09-22T21:09:49.477 回答