[R] Newbie woes with *apply

Gabor Grothendieck ggrothendieck at gmail.com
Sun Feb 14 20:40:34 CET 2010


Your function is not receiving what you may think its receiving.  Try this:

> x <- Sys.Date() + 1:3
> junk <- lapply(x, print)
[1] 14655
[1] 14656
[1] 14657

So add this as the first statement in the body of each of your functions:
date <- as.Date(date, "1970-01-01")

and then using x from above try these:
lapply(x, first.day.of.quarter)
xx <- x; xx[] <- sapply(x, first.day.of.quarter)






On Sun, Feb 14, 2010 at 8:59 AM, Dimitri Shvorob
<dimitri.shvorob at gmail.com> wrote:
>
> Dataframe cust has Date-type column open.date. I wish to set up another
> column, with (first day of) the quarter of open.date.
>
> To be comprehensive (of course, improvement suggestions are welcome),
>
> month = function(date)
> {
>  return(as.numeric(format(date,"%m")))
> }
>
> first.day.of.month = function(date)
> {
>  return(date + 1 - as.numeric(format(date,"%d")))
> }
>
> first.day.of.quarter = function(date)
> {
>  t = seq.Date(first.day.of.month(date), by = "-1 month", length =
> month(date) %% 3)
>  return(t[length(t)])
> }
>
> Now the main part,
>
>> cust$open.quarter  = apply(cust$open.date, 1, FUN = first.day.of.quarter)
> Error in apply(cust$open.date, 1, FUN = first.day.of.quarter) :
>  dim(X) must have a positive length
>
>> cust$open.quarter  = tapply(cust$open.date, FUN = first.day.of.quarter)
> Error in tapply(cust$open.date, FUN = first.day.of.quarter) :
>  element 1 is empty;
>   the part of the args list of 'is.list' being evaluated was:
>   (INDEX)
>
>> cust$open.quarter  = lapply(cust$open.date, FUN = first.day.of.quarter)
> Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L,  :
>  invalid 'trim' argument
>
> Can anyone suggest the right syntax?
>
> Thank you.
>
> --
> View this message in context: http://n4.nabble.com/Newbie-woes-with-apply-tp1555149p1555149.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org 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.
>



More information about the R-help mailing list