> I suppose it is just some basic matter of indexing language, something like
> 
> X3<- as.numeric ( ID[n] <= ID[n-1])
> 
> but it is not so simple!

If you first define 'n' as
   n <- seq_along(ID)[-1] # 2:length(ID)
then that code works.

> with(Data, { n <- seq_along(ID)[-1] ; as.numeric ( ID[n] <= ID[n-1]) }) 
[1] 0 0 1 0 1 1 0 0

You may want to put a NA at the start of the result so it has
the same length as the other columns in the data.frame.

I usually find it more convenient to leave things like ID[n]<=ID[n-1]
as logical variables instead of converting them to numbers.  Most
functions do the conversion implicitly if required and leaving them
as logicals helps me remember the meaning.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: [email protected] [mailto:[email protected]] On 
> Behalf
> Of Paolo Donatelli
> Sent: Monday, January 07, 2013 5:34 AM
> To: [email protected]
> Subject: [R] Refer to previous row
> 
> Hi all,
> 
> I have a very basic doubt -- but still, I am a newby!
> 
> My question is about referring to the previous row: in a sample as the
> following...
> 
> ID  X1  X2
> 1   A   12
> 2   A   6
> 3   A   10
> 1   B   17
> 2   B   19
> 1   C   22
> 1   D   13
> 2   D   19
> 3   D   21
> 
> ... I would like to create a dummy variable equal to 1 whenever the
> value of ID of the current row is lower or equal than the value of ID
> of the previous row -- check the new vector X3 I'd like to obtain:
> 
> ID  X1  X2  X3
> 1   A   12  0
> 2   A   6    0
> 3   A   10  0
> 1   B   17  1
> 2   B   19  0
> 1   C   22  1
> 1   D   13  1
> 2   D   19  0
> 3   D   21  0
> 
> I have searched a lot without finding a decent and working solution. I
> suppose it is just some basic matter of indexing language, something
> like
> 
> X3<- as.numeric ( ID[n] <= ID[n-1])
> 
> but it is not so simple!
> 
> 
> thanks!
> Paolo
> 
> ______________________________________________
> [email protected] 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.

______________________________________________
[email protected] 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.

Reply via email to