如何使用sqldf包

时间:2015-07-14 13:24:55

标签: r sqldf

我尝试使用sqldf包和月份函数来获取基于日期分组的视图但我收到错误:Error in sqliteSendQuery(con, statement, bind.data) : error in statement: no such function: month

以下是我的问题:s<-sqldf("select month(dateTime),sum(wolfs) group by dateTime")

附件是一个玩具数据框:

 df <- read.table(text = "dateTime         birds    wolfs     snakes
                         2014-05-21        9         7    a
                         2014-04-28        8         4    b
                         2014-04-13        2         8    c
                         2014-03-12        2         3    a
                         2014-02-04        8         3    a
                         2014-02-29        1         2    a
                         2014-01-17        7         1    b
                         2014-01-16        1         5    c
                         2014-09-20        9         7    c
                         2014-08-21        8         7    c ",header = TRUE)

如何使用sqldf包提取月份?

1 个答案:

答案 0 :(得分:3)

我怀疑你习惯了SQL Server,但你的案例中使用的sqldf后端是SQLite,其中没有MONTH函数。试试这个:

R> sqldf("SELECT strftime('%m', dateTime) AS Month
            ,SUM(wolfs) AS Wolves
         FROM df
         GROUP BY strftime('%m', dateTime)")
#    Month Wolves
#  1    01      6
#  2    02      5
#  3    03      3
#  4    04     12
#  5    05      7
#  6    08      7
#  7    09      7