[R] (Newbie) Functions on vectors

Vivek Satsangi vivek.satsangi at gmail.com
Fri Feb 17 21:23:41 CET 2006


Folks,

I want to make the following function more efficient, by vectorizing it:

getCriterionDecisionDate <- function (quarter , year)
{
  if (length(quarter) != length(year)) stop ("Quarter and year vectors
of unequal length!");
  ret <- character(0);

  for (i in 1:length(quarter)) {
    currQuarter <- quarter[i];
    currYear <- year[i];

    if ((currQuarter < 1) | (currQuarter > 4)) stop ("Invalid quarter!");
    if ((currYear < 1986) | (currYear > 2004)) stop ("Invalid year!");

    # If the criterion date is 1Q2004, then the reports were for periods
    # ending in Feb, March and April 2004 and the decision date is July 1, 2004.
    if (currQuarter == 1) {
      ret <- c(ret,paste("06/30/",currYear,sep=""));
    } else if (currQuarter == 2) {
      ret <- c(ret,paste("09/30/",currYear,sep=""));
    } else if (currQuarter == 3) {
      ret <- c(ret,paste("12/31/",currYear,sep=""));
    } else if (currQuarter == 4) {
      ret <- c(ret,paste("3/31/",currYear+1,sep=""));
    }
  }

  ret;
}


How can I make the 'if' statements work on vectors rather than using
one value at a time? (sorry, my copy of MASS is at home).

--
-- Vivek Satsangi
Student, Rochester, NY USA




More information about the R-help mailing list