[R] how to show date with this subset

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Feb 22 17:28:05 CET 2007


On Fri, 23 Feb 2007, Alfonso Sammassimo wrote:

> Dear List,
>
> Thankyou to Jim and Marc for their help on my previous question.
>
> I have a data frame of five columns, the first being a list of dates and the
> other four columns are numeric values. I wanted to list the days where all 4
> columns of values are less than in the previous row. I used the following
> which works fine, except it doesnt show the dates for each row (the values
> from column 1).
>
> differences <- apply(x, 2, diff)

Please don't use apply() columnwise on data frames: it turns them into 
matrices. Here you could use

tmp <- lapply(x[2:5], diff)
ind <- do.call("pmax", tmp) < 0 
x[c(FALSE, ind), ]

> all.lower.diffs <- subset(differences, apply(differences, 1,
> function(x){all(x<0)}
>
> I tried using the following loop instead, but it would only apply to the
> first column of every row("warning condition has length>1 and only first
> element will be used"):
>
> for ( i in 2:length(x[,1]))  if (x[i,]<x[i-1,]) {print(x[i,])}
                                    ^all(        ^)

> How can I resolve with either method? Any help much appreciated.
>
> Regards,
> Alf Sammassimo.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list