[R] Lookup prior value in data.frame (was: Dismiss previous email)

Gabor Grothendieck ggrothendieck at gmail.com
Sat Dec 1 03:06:11 CET 2007


Assuming that there is a -1 day for every day
in the data frame and all the -1 days are at
the beginning, try this where k[match(id, id)]
is the vector of corresponding day -1 k-values:

DF <- data.frame(id = c(56, 63, 73, 56, 63),
	day = c(-1, -1, -1, 2, 2),
	k = c(566, 680, 773, 298, 273))

transform(DF, percent = 100 * k / k[match(id, id)] - 100)

Also, please use meaningful subject headings so
that future persons having the same problem can
more easily locate it in the archive.

On Nov 30, 2007 8:44 PM, Judith Flores <juryef at yahoo.com> wrote:
> Sorry about that, it was sent by accident.
>
> I have a data frame that looks something like this:
>
>   id day    k
>  56  -1  566
>  63  -1  680
>  73  -1  773
>  56   2  298
>  63   2  273
>
>    Of course, it is a very simplified version of the
> real data frame I am working on. I need to add another
> column that would represent a percent change in k from
> day -1, by id. I put only two ids at day 2 to
> emphasize the fact that after day -1 some subjects
> won't be on the data frame any more.
>
> I tried something like this:
>
> pck<-by(dat,dat[,c("id","day")], function(x) {
>      pc<-((x$k-x$k[x$day==-1])/x$k[x$day==-1])*100
>      })
> but it didn't work.
>
> Then I tried:
>
> for(i in dat$id) {
>
>    for(s in dat$day) {
>        pc<-((dat$k[dat$id==i &
> dat$day==s]-dat$k[dat$id==i &
> dat$day==-1])/dat$k[dat$id==i & dat$day==-1])*100
> }
> }
> without success.
>
> I am sure it is very simple to do, but I would
> appreciate any hints.
>
> Thank you,
>
> Judith
>
>
>
>
>
>
>      ____________________________________________________________________________________
> Be a better pen pal.
>
> ______________________________________________
> 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