从循环创建数据框

时间:2013-08-15 04:31:13

标签: r date loops dataframe subset

如何为wkend创建数据框而不是打印它?

wkend<-as.Date(c("2013-01-04","2013-01-05","2013-01-06"),"%Y-%m-%d")
while(wkend < "2013-12-27") { 
   wkend <- wkend + 7
print(wkend)
 }

1 个答案:

答案 0 :(得分:3)

如果您想拥有data.frame,则需要将您的最后一天调整为1,否则您将有不均匀的行。但您可以使用lapplyseq.Date函数应用于wkend向量中的每个元素,如下所示:

df <- data.frame( lapply( wkend , seq , to = as.Date( "2013-12-26" , "%Y-%m-%d" ) , by = 7 ) )
names( df ) <- c("Col1","Col2","Col3") # Call the columns whatever you want
head(df)
    Col1       Col2       Col3
1 2013-01-04 2013-01-05 2013-01-06
2 2013-01-11 2013-01-12 2013-01-13
3 2013-01-18 2013-01-19 2013-01-20
4 2013-01-25 2013-01-26 2013-01-27
5 2013-02-01 2013-02-02 2013-02-03
6 2013-02-08 2013-02-09 2013-02-10