DATEPART(...)
is part of Transact-SQL which is proprietary to Microsoft and Sybase, so, no, it is not supported in sqldf
.
sqldf
works by creating a temporary database based on whichever engine is defined in the drv=
argument. So whatever version of SQL is supported by that engine, should be supported by sqldf
. See the documentation for a list of supported engines. If you don't specify an engine, it supports the vocabulary defined in SQLite, which is a subset of the standard SQL language (documentation here).
One problem in your example is that your ORDER_TIME values use the 12-hour time format. SQLite supports ISO-8601 which requires the 24-hour format. So, in your specific case, the only option I can think of is to create an HOURS
column in R and use that in the call to sqldf(...)
.
library(sqldf)
# create sample data...
set.seed(1)
# ORDER_TIME in 12-hour format; does not conform with ISO-8601
data <- data.frame(ORDER_TIME=strftime(as.POSIXct("1:00:00",format="%H:%M:%S")+seq(12*3600,24*3600,60),format="%I:%M:%S %p"),
ORDER.DATE=strftime(as.Date("2013-01-01")+rep(0:30,each=721),format="%m/%d/%Y"),
DISCHARGE_UNIT=sample(1:10,721,replace=T))
# add hours column based on ORDER_TIME
data$HOURS <- as.numeric(strftime(as.POSIXct(data$ORDER_TIME,format="%I:%M:%S %p"),format="%H"))
sqldf("select DISCHARGE_UNIT,
round(avg(HOURS),2) `avg order time`
from data
group by DISCHARGE_UNIT")
# DISCHARGE_UNIT avg order time
# 1 1 16.91
# 2 2 16.69
# 3 3 16.64
# 4 4 17.10
# 5 5 15.78
# 6 6 15.01
# 7 7 17.09
# 8 8 15.12
# 9 9 17.68
# 10 10 17.17
If your time data was in 24-hour format (highly recommended, by the way), then you could use the SQLite date and time functions:
set.seed(1)
# ORDER_TIME in 24-hour format; conforms to ISO-8601
data <- data.frame(ORDER_TIME=strftime(as.POSIXct("1:00:00",format="%H:%M:%S")+seq(12*3600,24*3600,60),format="%H:%M:%S"),
ORDER.DATE=strftime(as.Date("2013-01-01")+rep(0:30,each=721),format="%m/%d/%Y"),
DISCHARGE_UNIT=sample(1:10,721,replace=T))
sqldf("select DISCHARGE_UNIT,
round(avg(strftime('%H',ORDER_TIME)),2) `avg order time`
from data
group by DISCHARGE_UNIT",drv="SQLite")
# DISCHARGE_UNIT avg order time
# 1 1 16.91
# 2 2 16.69
# 3 3 16.64
# 4 4 17.10
# 5 5 15.78
# 6 6 15.01
# 7 7 17.09
# 8 8 15.12
# 9 9 17.68
# 10 10 17.17