2016-04-07 11 views
0

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 

答えて

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 
+0

おかげで、私は試してみましょう。 –

+0

絶対に、私が探していたものです。しかし、1つの質問は、 'list'として返されています、どのようにdata.frameとしてすべての異なるリストを保存するのですか? –

+1

@ノア彼らはデータフレームです。試してみましょう 'mylist [[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)) 
+0

その新しい図書館私は知らなかった、ありがとう。 –