计算 R 中每天、每月和每年的观察次数

Dan*_*ood 6 r

我有以下形式的数据框(它太大了,无法完全张贴在这里):

      listing_id    date    city    type    host_id availability
1   703451  25/03/2013  amsterdam   Entire home/apt 3542621 245
2   703451  20/04/2013  amsterdam   Entire home/apt 3542621 245
3   703451  28/05/2013  amsterdam   Entire home/apt 3542621 245
4   703451  15/07/2013  amsterdam   Entire home/apt 3542621 245
5   703451  30/07/2013  amsterdam   Entire home/apt 3542621 245
6   703451  19/08/2013  amsterdam   Entire home/apt 3542621 245
Run Code Online (Sandbox Code Playgroud)

等等...

我想要三个新的数据框。一个计算特定年份(2013、2012、2011 等)的观测次数,另一个是每月(07/2013、06/2013 等),另一个是每天(28/05/2013、29/05/ 2013 年等)。我只想计算单位时间内出现的次数。

我该怎么做?

akr*_*run 3

我们可以将“日期”列转换为类,使用fromDate提取,使用from获取月年。我们将“dates”、“yr”、“monyr”放入循环中( ),并使用 来在原始数据集 ('df1') 中创建出现次数列的计数。最好将数据集放在. 但是,如果您坚持的话,我们可以使用多个对象来重载全局环境。year?yearlibrary(lubridate)as.yearmonlibrary(zoo)listlapplyavelistlist2env

library(zoo)
library(lubridate)
dates <- as.Date(df1$date, '%d/%m/%Y')
yr <- year(dates)
monyr <- as.yearmon(dates)
lst <- lapply(list(dates, yr, monyr), function(x) 
       transform(df1, Count=ave(seq_along(x), x, FUN= length)))
names(lst) <- paste0('newdf', seq_along(lst))
list2env(lst, envir=.GlobalEnv)
Run Code Online (Sandbox Code Playgroud)