Hi, I would like to fix the data in the following data.frame, and I am having trouble coding this in R - help please!> xA B x y z 1 1 10.0 100 1000 10000 2 2 19.8 200 2000 20000 3 3 20.1 300 3000 30000 4 4 20.3 400 4000 40000 5 5 30.0 500 5000 50000 Column B is the problem. The logic I need to apply (this is in pseudo code ... I don't know how to do this in R) for all rows, r if x$B[r] <= x$B[r-1] + a then x$B[r] = x$B[r-1] i.e. If a=1, then I would end up with the data.frame> xA B x y z 1 1 10.0 100 1000 10000 2 2 19.8 200 2000 20000 3 3 19.8 300 3000 30000 4 4 19.8 400 4000 40000 5 5 30.0 500 5000 50000 Many thanks in advance for any help, Regards, David
Petr PIKAL
2007-Oct-08 13:05 UTC
[R] Odp: How to change row value based on previous row value
Hi r-help-bounces at r-project.org napsal dne 08.10.2007 14:24:13:> Hi, > > I would like to fix the data in the following data.frame, and I am > having trouble coding this in R - help please! > > > x > A B x y z > 1 1 10.0 100 1000 10000 > 2 2 19.8 200 2000 20000 > 3 3 20.1 300 3000 30000 > 4 4 20.3 400 4000 40000 > 5 5 30.0 500 5000 50000 > > Column B is the problem. > > The logic I need to apply (this is in pseudo code ... I don't know how > to do this in R) > > for all rows, r > if x$B[r] <= x$B[r-1] + a > then x$B[r] = x$B[r-1] > > i.e. If a=1, then I would end up with the data.frame > > > x > A B x y z > 1 1 10.0 100 1000 10000 > 2 2 19.8 200 2000 20000 > 3 3 19.8 300 3000 30000 > 4 4 19.8 400 4000 40000 > 5 5 30.0 500 5000 50000Maybe not the simplest one:> test<-read.table("clipboard") > testA B x y z 1 1 10.0 100 1000 10000 2 2 19.8 200 2000 20000 3 3 20.1 300 3000 30000 4 4 20.3 400 4000 40000 5 5 30.0 500 5000 50000> b.na <- test$B > b.na[c(F,diff(test$B)<1)] <- NA > b.na[1] 10.0 19.8 NA NA 30.0> library(zoo) > b.na <- na.locf(b.na)[1] 10.0 19.8 19.8 19.8 30.0 and you can put the vector back do data frame by test$B<-b.na But it works only if there are chunks of values separated by larger steps. Regards Petr> > Many thanks in advance for any help, > > Regards, > David > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html> and provide commented, minimal, self-contained, reproducible code.