R 按月份和年份分组

R 按月份和年份分组,r,R,我假设这是一个非常简单的转换,但我无法正确实现: 我在一个数据表中有两列。一个包含日期,另一个包含一些唯一的数字。我基本上知道特定月份和年份的行数 我想知道2011-02年度的读数,然后是2011-03年度的读数,依此类推 以下是一些免费数据: set.seed(1) df <- data.frame( x = sample(Sys.Date()-0:120, 20, TRUE), y = sample(100, 20, TRUE) ) 或使用基本Raggregate(

我假设这是一个非常简单的转换,但我无法正确实现:

我在一个数据表中有两列。一个包含日期,另一个包含一些唯一的数字。我基本上知道特定月份和年份的行数

我想知道2011-02年度的读数,然后是2011-03年度的读数,依此类推

以下是一些免费数据:

set.seed(1)
df <- data.frame(
    x = sample(Sys.Date()-0:120, 20, TRUE),
    y = sample(100, 20, TRUE)
) 
或使用基本R
aggregate()


这里有一种不同的方法,使用
groupby
。如果您感兴趣,我还可以使用
lubridate
设置POSIX日期对象

library(lubridate)
library(dplyr)

# create some data
data <- data.frame("dates" = ymd(c("2014-05-01","2014-05-01","2014-05-01","2014-06-02","2014-06-02")), 
                   "values" = c(1,3,5,2,5))

# this is the actual summarize. 
data %>% group_by(dates) %>% summarise(n = n())

请提供一个可复制的例子。给我们你的数据框。
aggregate(list(N = df$y), list(month = format(df$x, "%Y-%m")), length)
#     month N
# 1 2015-06 4
# 2 2015-07 7
# 3 2015-08 4
# 4 2015-09 5
library(lubridate)
library(dplyr)

# create some data
data <- data.frame("dates" = ymd(c("2014-05-01","2014-05-01","2014-05-01","2014-06-02","2014-06-02")), 
                   "values" = c(1,3,5,2,5))

# this is the actual summarize. 
data %>% group_by(dates) %>% summarise(n = n())
       dates     n
      (time) (int)
1 2014-05-01     3
2 2014-06-02     2