[R] Insert value from same column of another row (lag across observations)

From: David L. Van Brunt, Ph.D. <dlvanbrunt_at_gmail.com>
Date: Mon 10 Oct 2005 - 05:14:50 EST


I know I've done this before, but it's been a while and I can't find quite what I need in the help files or archives.

I have a text field in a very large data frame. I'd like to add a column that represents the value from an existing field, from the next record (the data are sorted). I'm trying to represent "what happens tomorrow", so the "today" row would have an "NA" value (unknown).

So if x is:
> x
[,1]
[1,] "today"
[2,] "yesterday"
[3,] "the day before"
[4,] "two days before"

any y is
> cbind(x,c(1,2,3,4))
[,1] [,2]
[1,] "today" "1"
[2,] "yesterday" "2"
[3,] "the day before" "3"
[4,] "two days before" "4"

z should become

[,1] [,2] [,3]
[1,] "today" "1" "NA"
[2,] "yesterday" "2" "1"
[3,] "the day before" "3" "2"
[4,] "two days before" "4" "3"

I've tried
z<-cbind(y,c("NA",y[-1,2]))

but I get
[1,] "today" "1" "NA"
[2,] "yesterday" "2" "2"
[3,] "the day before" "3" "3"
[4,] "two days before" "4" "4"

So the "lagging" doesn't work.

Any ideas?

--
---------------------------------------
David L. Van Brunt, Ph.D.
mailto:dlvanbrunt@gmail.com

	[[alternative HTML version deleted]]

______________________________________________
R-help@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
Received on Mon Oct 10 05:22:37 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:40:40 EST