如何在R中基于月 - 年框架划分数据帧

时间:2016-04-07 14:58:45

标签: r date

我的dataframe包含日期date类型。我想根据每个月将dataframe划分为n个不同的数据框(df1, df2, ......,dfn),这样我就可以分别对每个月的每一个进行进一步处理。值得注意的是,同一个月的不同年份会有所不同。一个循环会很好,因为可能有无限的日期。请给我一些建议。我不明白我该怎么办。

dates <- as.Date(c("2015-05-01", "2015-05-15","2016-05-01", "2016-05-15","2016-06-02", "2016-06-12"))
names <- c("Mr A", "Ms B", "", "Ms C", "Mr K", "Mr S")
comments <- c("first comment", "", "third comment", "fourth comment", "fifth comment", "sixth comment")
like <- as.integer(c(2,4,0,6,0,3))
df <- data.frame(dates, names, comments, like, stringsAsFactors = FALSE)

## classification according to month, for each particular year
# df[order(as.Date(df$dates, format="%Y-%m-%d")),] # it sorts dataframe, not what I need

# df1 <- subset(df, as.Date(dates) < as.Date("2015-05-31"))
# print(df1)
# df2 <- subset(df, as.Date(dates)<as.Date("2016-05-31"))
# print(df2)
# df3 <- subset(df, as.Date(dates) < as.Date("2016-06-01"))
# print(df3)

e.g。首先,df1应该是这样的,

       dates names      comments like
1 2015-05-01  Mr A first comment    2
2 2015-05-15  Ms B                  4

2 个答案:

答案 0 :(得分:1)

这样的东西?

library(zoo)
split(df,as.yearmon(df$dates))
$`Mai 2015`
       dates names      comments like
1 2015-05-01  Mr A first comment    2
2 2015-05-15  Ms B                  4

$`Mai 2016`
       dates names       comments like
3 2016-05-01        third comment    0
4 2016-05-15  Ms C fourth comment    6

$`Jun 2016`
       dates names      comments like
5 2016-06-02  Mr K fifth comment    0
6 2016-06-12  Mr S sixth comment    3

答案 1 :(得分:1)

library(lubridate)
a <- ymd("2015-05-01", tz = "UTC") + months(0:11)
b <- ymd("2015-05-01", tz = "UTC") + months(0:11) + days(14)
sort(c(a,b))