以下是我的数据:
Item Date
Apple 09/06/2015
Orange 19/06/2015
Pear 01/09/2015
Kiwi 20/10/2015
我想在R中的Date列中按月和年计算项目。
以下是我想要实现的输出:
Date Frequency
05/2015 0
06/2015 2
07/2015 0
08/2015 0
09/2015 1
10/2015 1
谢谢。
答案 0 :(得分:3)
只需确保您使用正确格式的日期,然后您可以使用cut
和table
,以及一些格式,如果您想缩短日期,
## Convert to date
dat$Date <- as.Date(dat$Date, format="%d/%m/%Y")
## Tabulate
tab <- table(cut(dat$Date, 'month'))
## Format
data.frame(Date=format(as.Date(names(tab)), '%m/%Y'),
Frequency=as.vector(tab))
# Date Frequency
# 1 06/2015 2
# 2 07/2015 0
# 3 08/2015 0
# 4 09/2015 1
# 5 10/2015 1
答案 1 :(得分:1)
假设您在每月总计之后,我会使用lubridate
和dplyr
:
library(lubridate)
library(dplyr)
data$Date <- dmy(data$Date)
data$date_formatted <- format(data$Date, "%m/%Y")
data %>% group_by(date_formatted) %>% summarise(frequency = n())
这给出了以下输出:
date_formatted frequency
1 06/2015 2
2 09/2015 1
3 10/2015 1