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

jcrosbie james at crosb.ie
Wed Mar 19 20:57:05 CET 2014


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)






--
View this message in context: http://r.789695.n4.nabble.com/How-to-fix-the-warning-message-the-condition-has-length-1-and-only-the-first-element-will-be-used-tp4687140.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list