[R] Newbie woes with *apply

Dimitri Shvorob dimitri.shvorob at gmail.com
Sun Feb 14 14:59:07 CET 2010


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.



More information about the R-help mailing list