簡體   English   中英

在R中每天,每月和每年的觀察次數計數

[英]Count number of observations per day, month and year in 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

等等...

我想要三個新的數據框。 一個統計特定年份(2013、2012、2011等)的觀測值,另一個統計每月(07 / 2013、06 / 2013等),另一個統計每天(28/05 / 2013,29 / 05 /) 2013等)。 我只想計算每單位時間發生的次數。

我該怎么做?

使用data.table ,這非常簡單:

library(data.table)
dt <- fread("listing_id    date    city    type    host_id availability
703451  25/03/2013  amsterdam   Entire_home/apt 3542621 245
703451  20/04/2013  amsterdam   Entire_home/apt 3542621 245
703451  28/05/2013  amsterdam   Entire_home/apt 3542621 245
703451  15/07/2013  amsterdam   Entire_home/apt 3542621 245
703451  30/07/2013  amsterdam   Entire_home/apt 3542621 245
703451  19/08/2013  amsterdam   Entire_home/apt 3542621 245")
dt$date <- as.Date(dt$date, "%d/%m/%Y")

dt[, .N, by=year(date)] 
#    year N
# 1: 2013 6

dt[, .N, by=.(year(date), month(date))] 
#    year month N
# 1: 2013     3 1
# 2: 2013     4 1
# 3: 2013     5 1
# 4: 2013     7 2
# 5: 2013     8 1

dt[, .N, by=date] # or: dt[, .N, by=.(year(date), month(date), day(date)] 
#          date N
# 1: 2013-03-25 1
# 2: 2013-04-20 1
# 3: 2013-05-28 1
# 4: 2013-07-15 1
# 5: 2013-07-30 1
# 6: 2013-08-19 1

我們可以在“日期”列轉換為Date類,提取year使用?yearlibrary(lubridate)使用獲得月-年as.yearmonlibrary(zoo) 我們將'date','yr','monyr'放入list ,循環遍歷( lapply ),然后使用ave在原始數據集('df1')中創建出現次數列。 最好將數據集放在list 但是,如果您堅持認為,我們可以使用list2env在全局環境中添加多個對象。

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)

將索引獲取為Postxct格式,然后:

counts <- data.frame(table(as.Date(index(my_data_frame))))

根據需要更改as.Date

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM