[R] Confusion with sapply

From: Patnaik, Tirthankar <tirthankar.patnaik_at_citi.com>
Date: Wed, 13 Jun 2007 12:31:38 +0530


Hi,
 I have some confusion in applying a function over a column.

Here's my function. I just need to shift non-March month-ends to March month-ends. Initially I tried seq.dates, but one cannot give a negative increment (decrement) here.

return(as.Date(seq.dates(format(xdate,"%m/%d/%Y"),by="months",len=4)[4]) )

Hence this simple function:

> mydate <- as.Date("2006-01-01")
>
> # Function to shift non-March company-reporting dates to March.
> Set2March <- function(xdate){

+ # Combines non-March months into March months:
+ # Dec2006 -> Mar2007
+ # Mar2006 -> Mar2006
+ # Jun2006 -> Mar2006
+ # Sep2006 -> Mar2006
+ # VERY Specific code.
+     Month <- format(xdate,"%m")
+     wDate <- month.day.year(julian(xdate))
+     if (Month=="12"){
+         wDate$year <- wDate$year + 1
+         wDate$month <- 3
+     }else
+     if (Month=="06"){
+         wDate$month <- 3
+     }else
+     if (Month=="09"){
+         wDate$month <- 3
+         wDate$day <- wDate$day + 1
+     }else warning ("No Changes made to the month, since month is not
one of (6,9,12)")
+     cDate <- chron(paste(wDate$month,wDate$day,wDate$year,sep="/"))
+     return(as.Date(as.yearmon(as.Date(cDate,"%m/%d/%y")),frac=1))
+ }
> Set2March(as.Date("2006-06-30"))

[1] "2006-03-31"
> Set2March(mydate)

[1] "2006-01-31"
Warning message:
No Changes made to the month, since month is not one of (6,9,12) in: Set2March(mydate)
>

Works well when I use it on a single date. Then I try it on a vector:

> dc <- seq(as.Date("2006-01-01"),len=10, by="month")
> dc

 [1] "2006-01-01" "2006-02-01" "2006-03-01" "2006-04-01" "2006-05-01" "2006-06-01" "2006-07-01" "2006-08-01"
 [9] "2006-09-01" "2006-10-01"

> sapply(as.vector(dc),Set2March)

Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3, :

        unimplemented type 'character' in 'asLogical'
>

What am I missing here? Shouldn't the function work with the sapply working on each entry?

TIA and best,
-Tir



R-help_at_stat.math.ethz.ch 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. Received on Wed 13 Jun 2007 - 07:13:13 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 13 Jun 2007 - 14:31:55 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.