错误在 R sqldf 包中使用 datename/datepart

ERROR use datename/datepart in R sqldf package

当我 运行 sqldf 包用于 datename 或 datepart 时出现错误消息。 这是我用的table。

Height Date
163  12/01/90
182  11/13/88
167   5/14/97
172   3/18/94
170  10/11/92 
185   7/15/90


expected_table <-sqldf("select 
               [Height],
               (datename(weekday,[Date])) AS [Day of Week]
               from table1

               ")

Error in sqliteSendQuery(con, statement, bind.data) : 
  error in statement: no such column: weekday                     

如果没有,是否有任何方法可以从 [Date] 获取工作日?

sqldf 是一个薄层,它将数据和 SQL 语句传递到您选择的后端。默认后端是 sqlite,但它也支持 H2、PostgreSQL 和 MySQL。 SQLite 不支持 datename 但 H2 支持 dayname:

# reproducibly set up input data frame 
Lines <- "Height Date
163  12/01/1990
182  11/13/1988
167   5/14/1997
172   3/18/1994
170  10/11/1992 
185   7/15/1990"
DF <- read.table(text = Lines, header = TRUE)
DF$Date <- as.Date(DF$Date, "%m/%d/%Y")  # Date class

library(RH2)  # if RH2 is loaded sqldf will automatically use H2 instead of sqlite
library(sqldf)

sqldf("select *, dayname(Date) Weekday from DF")

给予:

  Height       Date   Weekday
1    163 1990-12-01  Saturday
2    182 1988-11-13    Sunday
3    167 1997-05-14 Wednesday
4    172 1994-03-18    Friday
5    170 1992-10-11    Sunday
6    185 1990-07-15    Sunday

注:当然直接R也很容易做到:

transform(DF, Weekday = format(Date, "%A"))

给予:

  Height       Date   Weekday
1    163 1990-12-01  Saturday
2    182 1988-11-13    Sunday
3    167 1997-05-14 Wednesday
4    172 1994-03-18    Friday
5    170 1992-10-11    Sunday
6    185 1990-07-15    Sunday