[R] Help on manipulating a data frame

Gabor Grothendieck ggrothendieck at gmail.com
Mon Apr 23 06:31:23 CEST 2007


Do you mean you want to return the first row for each mont for
which the value > 0?

In that case try this.  The first group of lines recreates your
data frame and calls it DF.  by causes f to operate on a subset of
rows comprising one month extracting the first row for which
the value is positive and also adding in the week number.
do.call rbinds the results from each month altogether.

Input <- "2007-01-05 -1.52377151
2007-01-12  1.04787390
2007-01-19  0.61647047
2007-01-26  1.87864283
2007-02-02  0.54992405
2007-02-09  1.96850069
2007-02-16  0.26850159
2007-02-23  1.56305144
2007-03-02 -4.19500573
2007-03-09  0.77127814
2007-03-16  0.32387312
2007-03-23  2.02163219
2007-03-30  0.63175605
2007-04-06  1.33346284
2007-04-13  0.96021569"
DF <- read.table(textConnection(Input), col.names = c("Date", "Value"),
	colClasses = c("Date", "numeric"))

f <- function(x) cbind(x, Week = seq_len(nrow(x)))[which.max(x$Value > 0),]
do.call("rbind", by(DF, format(DF$Date, "%Y-%m"), f))

On 4/22/07, Alfonso Sammassimo <cincinattikid at bigpond.com> wrote:
> Hi R-experts,
>
>
>
> I have a large set of weekly data in this format:
>
>
>
> 2007-01-05 -1.52377151
> 2007-01-12  1.04787390
> 2007-01-19  0.61647047
> 2007-01-26  1.87864283
> 2007-02-02  0.54992405
> 2007-02-09  1.96850069
> 2007-02-16  0.26850159
> 2007-02-23  1.56305144
> 2007-03-02 -4.19500573
> 2007-03-09  0.77127814
> 2007-03-16  0.32387312
> 2007-03-23  2.02163219
> 2007-03-30  0.63175605
> 2007-04-06  1.33346284
> 2007-04-13  0.96021569
>
>
>
> How might this data be sorted to something like this?:
>
>
>
> Date               Week of Month     Value
>
> 2007-01-05          1                     -1.52377151
> 2007-01-12          2                      1.04787390
> 2007-01-19          3                      0.61647047
> 2007-01-26          4                      1.87864283
>
> 2007-02-02          1                      0.54992405
>
>
>
> My aim is to return the last value of every month where the previous values
> in that month were negative values, hence the need to split the data by
> month. Any guide as to how this might this be possible without a loop?
>
>
>
> Any help would be much appreciated.
>
>
>
> Thanks,
>
>
>
> Alf Sammassimo
>
> Melbourne, Australia
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list