How to fix the warning message "the condition has length > 1 and only the first element will be used"?

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

How to fix the warning message "the condition has length > 1 and only the first element will be used"?

jcrosbie
I'm trying to create a function to return the date x months in the past.

With the code below I'm getting the warning message:

Warning message:
In if (MonthsBack >= CurrentMonth) { :
  the condition has length > 1 and only the first element will be used


##############################

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)


Reply | Threaded
Open this post in threaded view
|

Re: How to fix the warning message "the condition has length > 1 and only the first element will be used"?

bretschr
Hi jcrosbie ,


Re:


> I'm trying to create a function to return the date x months in the past.
>
> With the code below I'm getting the warning message:
>
> Warning message:
> In if (MonthsBack >= CurrentMonth) { :
> the condition has length > 1 and only the first element will be used
>

Use ifelse(), that's for vectors. "If" is intended for single elements only.

Best wishes,


Franklin
-



Franklin Bretschneider
Dept of Biology
Utrecht University
[hidden email]

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.