I am trying to write some code where the factor references its previous value, but can't find a solution searching through the archive.> Xfirst second 1 A 1 2 A 2 3 B 3 4 B 4 5 B 5 6 C 6 7 C 7 I need a third column, in pseudo code- If value of first=previous value of first: third=previous value of third else third = second So the third column would look like: 0 0 3 3 3 6 6 Thanks!
Hello, The solution to problem will seem far easier if you think in a different way. For instance, you may want to consider the extra dummy column previous.first.value <- c( "NA", first[ - length(first) ] ) Then you can "horizontally" compare first with it's previous value. Best regards, Carlos J. Gil Bellosta http://www.datanalytics.com On Mon, 2009-01-12 at 18:57 +1100, Heston Capital wrote:> I am trying to write some code where the factor references its > previous value, but can't find a solution searching through the > archive. > > > X > first second > 1 A 1 > 2 A 2 > 3 B 3 > 4 B 4 > 5 B 5 > 6 C 6 > 7 C 7 > > I need a third column, in pseudo code- > If value of first=previous value of first: > third=previous value of third > else third = second > > So the third column would look like: > 0 > 0 > 3 > 3 > 3 > 6 > 6 > > > Thanks! > > ______________________________________________ > 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.
Try this: X$third <- rep(X$second[which(!duplicated(X$first))], table(X$first)) On Mon, Jan 12, 2009 at 5:57 AM, Heston Capital <hestoncapital@gmail.com>wrote:> I am trying to write some code where the factor references its > previous value, but can't find a solution searching through the > archive. > > > X > first second > 1 A 1 > 2 A 2 > 3 B 3 > 4 B 4 > 5 B 5 > 6 C 6 > 7 C 7 > > I need a third column, in pseudo code- > If value of first=previous value of first: > third=previous value of third > else third = second > > So the third column would look like: > 0 > 0 > 3 > 3 > 3 > 6 > 6 > > > Thanks! > > ______________________________________________ > R-help@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. >-- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]]