【发布时间】:2015-09-29 20:34:39
【问题描述】:
我有这个功能:
pcal.getPeriodForDate <- function(date_) {
dateObject <- as.POSIXlt(date_)
calendarStart <- pcal.getCalendarStart(dateObject$year + 1900)
difference <- dateObject - calendarStart
if(difference < 0) {
calendarStart <- pcal.getCalendarStart(dateObject$year + 1899)
difference <- dateObject - calendarStart
}
period <- difference / 28
week <- ifelse(period < 1, ceiling(period * 4), ceiling((period - floor(period)) * 4))
return(list(Period = as.numeric(ceiling(period)), Week = week))
}
我还有一个结构如下的数据框
> str(sells)
'data.frame': 73738 obs. of 4 variables:
$ LOC_NBR: chr "2" "2" "2" "2" ...
$ SLS_DT : Date, format: "2015-02-01" "2015-02-02" "2015-02-03" "2015-02-04" ...
$ SALES : num 1 2 3 4 5 ...
我希望能够做到这一点:
sells$pd <- pcal.getPeriodForDate(sells$SLS_DT)$Period
但是,我收到大量警告:
Warning messages:
1: In if (year < 2000) { :
the condition has length > 1 and only the first element will be used
2: In seedYear:year :
numerical expression has 73738 elements: only the first used
3: In if (difference < 0) { :
the condition has length > 1 and only the first element will be used
4: In if (year < 2000) { :
the condition has length > 1 and only the first element will be used
5: In seedYear:year :
numerical expression has 73738 elements: only the first used
该函数在传递一个值时工作正常:
> pcal.getPeriodForDate('2015-09-29')
$Period
[1] 9
$Week
[1] 3
我怎样才能做到这一点?
【问题讨论】:
-
could not find function "pcal.getCalendarStart" -
最简单/最快的方法是矢量化函数
v <- Vectorize(pcal.getPeriodForDate)和v(sells$SLS_DT)