【问题标题】:How can I fix this error "the condition has length > 1 and only the first element will be used"?如何解决此错误“条件的长度> 1,并且只使用第一个元素”?
【发布时间】:2014-03-19 19:53:52
【问题描述】:

我正在编写一个函数来从当前日期查找 x 个月前的日期。我不断收到错误/警告。

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)

警告信息: 在 if (MonthsBack >= CurrentMonth) { : 条件的长度 > 1,并且只使用第一个元素

我将如何纠正这个错误?

【问题讨论】:

  • 该消息表示MonthsBackCurrentMonth 之一或两者都是向量。只有每个向量的第一个元素用于测试“if”条件。但是,您的真正 问题是在有可靠的、经过验证的工具到位的情况下尝试发明自己的日期时间函数。浏览 thedailywtf.com 以获取大量自制日期时间函数变坏的示例。
  • 您可以使用allany 来解决您的问题。例如:if(any(MonthsBack&gt;=CurrentMonth))。否则,我完全支持@CarlWitthoft cmets!

标签: r


【解决方案1】:

我也同意 CarlWitthoft 的评论,尽管似乎没有通过日期函数的简单答案。

代码中的问题是没有向量化的条件语句。您可以在没有 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"

【讨论】:

  • 不容易?伪代码:1)从 POSIXct 日期中提取“月”值。 2) 从该值中减去x。 3) 从原始日期字符串中减去 POSIXct 月份值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
相关资源
最近更新 更多