##把周一算作是第一天,[0,6]或者[1,7]ifelse(wday('2016-04-14')==1,6,wday('2016-04-14')-2)ifelse(wday('2016-04-14')==1,7,wday('2016-04-14')-1)##定义新函数DayOfWeek###函数功能-返回输入日期字符串同一周的7天的日期DayOfWeek<-function(dayString){##对输入的检查-异常处理--输入需是日期的字符串-ymd格式if(!is.character(dayString)){cat("the input data should be character!\n")}##将星期的开始日期设置为周一TransDay<-ifelse(wday(dayString)==1,7,wday(dayString)-1)##lastDayOfWeek<-ymd(dayString)-TransDay+8##lastDayOfWeek+days(-7:-1)##获取日期所在的周数中的星期一的日期firstDayOfWeek<-ymd(dayString)-TransDay+1##和日期在同一周的7天的日期firstDayOfWeek+days(0:6)}month(ymd('2016-04-17'))week(ymd('2016-04-17'))DayOfWeek('2016-04-17')week(ymd('2016-01-01'))week(ymd('2016-01-01'))##计算第几周的所在日期---可能含有误差--默认元旦是一年的第一周,不知道这个准确与否WeekFunc<-function(year,weekth){#if(!is.character(year)){#cat("the input data should be year!\n")#}year<-paste(year,"01-01",sep="-")time<-ymd(year)+ddays(7*weekth)time}DayofWeek<-as.character(WeekFunc(2016,24))DayOfWeek(DayofWeek)DayofWeek<-as.character(WeekFunc(2016,24))DayOfWeek(DayofWeek)