[R] Notation for previous observation in a data frame

Joshua Wiley jwiley.psych at gmail.com
Sun Jul 8 08:08:48 CEST 2012

Hi Ernie,

I'll use the built in mtcars dataset for demonstrative purposes.

You have some condition, which can be used to create an index

## show data frame
## create index based on your condition
i <- which(mtcars$carb == 1)
## set those rows of mtcars in your index
## to the index - 1
mtcars[i, ] <- mtcars[i - 1, ]
## show resulting data frame

note that if your condition grabs the first row, this will wreck havoc.



On Sat, Jul 7, 2012 at 8:20 PM, Ernie Tedeschi <ernie.tedeschi at gmail.com> wrote:
> I've created a data frame in R, but in order to clean up some of the data,
> I need to set certain variable observations equal to the value of their
> previous observation (it would be conditional, but that part's less
> important right now). In Stata, I would simply set var = var[_n-1] in those
> cases. What is the R equivalent?
>         [[alternative HTML version deleted]]
> ______________________________________________
> 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.

Joshua Wiley
Ph.D. Student, Health Psychology
Programmer Analyst II, Statistical Consulting Group
University of California, Los Angeles

More information about the R-help mailing list