I have a dataframe
contains dates, date
type. I want to divide the dataframe
into n
different dataframe ( df1, df2, ......,dfn
) according to each month thus I can do further process on each on the month separately. noticeable that, same month of different years will be different. A loop will be nice, as there may be unlimited dates. Please give me some suggestion. I cannot understand how should I proceed.
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)
eg first, df1 should be like this,
dates names comments like
1 2015-05-01 Mr A first comment 2
2 2015-05-15 Ms B 4
Something like this?
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
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.