[英]How to divide dataframe based on month-year frame in R
我有一個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)
例如,首先,df1應該像這樣,
dates names comments like
1 2015-05-01 Mr A first comment 2
2 2015-05-15 Ms B 4
像這樣嗎
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.