[R] Newbie woes with *apply
Gabor Grothendieck
ggrothendieck at gmail.com
Sun Feb 14 16:04:47 CET 2010
Try
library(zoo)
x <- as.Date(seq(1, 500, 50)) # test data
as.Date(as.yearmon(x))
as.Date(as.yearqtr(x))
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