[英]How can I fix this error “the condition has length > 1 and only the first element will be used”?
I am writing a function to find a date x months back form a current date. 我正在写一个函数来查找当前日期x个月之前的日期。 I keep getting an error/warning.
我不断收到错误/警告。
DateBack <- function(CurrentYear, CurrentMonth, MonthsBack){
if(MonthsBack< 13){
if(MonthsBack>=CurrentMonth){
month<-12+CurrentMonth-MonthsBack
datet<-paste(CurrentYear-1,month, sep="-")
}
else{
month<-CurrentMonth-MonthsBack
datet<-paste(CurrentYear-1, month, sep="-")
}
}
else{
Years <- trunc(MonthsBack/12,0)
if((MonthsBack-12*Years)>=CurrentMonth){
month<-12+CurrentMonth-MonthsBack
}
else{
month<-CurrentMonth-MonthsBack
}
datet<-paste(CurrentYear-Years, month, sep="-")
}
return(datet)
}
CurrentYear<- c(2000, 2000, 2003, 2004)
CurrentMonth<-c(1, 2, 6, 12)
df<- data.frame(CurrentYear, CurrentMonth)
df$MonthsBack <- DateBack(df$CurrentYear,df$CurrentMonth,1)
Warning message: In if (MonthsBack >= CurrentMonth) { : the condition has length > 1 and only the first element will be used 警告消息:如果if(MonthsBack> = CurrentMonth){:条件的长度> 1,则仅使用第一个元素
How would I go about correcting this error? 我将如何纠正该错误?
I second CarlWitthoft comment too, although there does not seem to be an easy answer through date functions. 我也同意CarlWitthoft的意见,尽管通过日期函数似乎没有一个简单的答案。
The issue in the code is the conditional statement which is not vectorized. 代码中的问题是未向量化的条件语句。 You can implement it with no IF statement in a fully vectorized manner:
您可以不使用IF语句以完全矢量化的方式实现它:
DateBack = function (Y,M, monthsBack) {
YM = (Y*12 + M - 1) - monthsBack
newY = YM %/% 12
newM = YM %% 12 + 1
return( paste( newY, newM, sep="-"))
}
DateBack( c(2000,2000,2003,2004),c(1,2,6,12),1)
[1] "1999-12" "2000-1" "2003-5" "2004-11"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.