[R] Refer to previous row

David Winsemius dwinsemius at comcast.net
Mon Jan 7 19:06:41 CET 2013


On Jan 7, 2013, at 5:33 AM, Paolo Donatelli wrote:

> 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

Something like (untested):

   dfrm$X3 <- c(0, as.numeric( diff(dfrm$ID) <= 0 ) )

That might be faster than this sort of untested strategy:

    ...   <- with(dfrm, c( 0 , as.numeric( ID[2:nrow(dfrm)] <= ID[1: 
(nrow(dfrm)-1] ) ) )

In my newbie days I thought a function named `lag` would do it, but  
discovered it was only working on ts-class objects.


>
> I have searched a lot without finding a decent and working solution.  
> I Adding
> suppose it is just some basic matter of indexing language, something
> like
>
> X3<- as.numeric ( ID[n] <= ID[n-1])

An explicit sequence rather than using mathematical notation is  
needed. And if you are using dataframes, you should not be using  
`attach`. That X3 would not be constructed in the dataframe.

-- 

David Winsemius, MD
Alameda, CA, USA




More information about the R-help mailing list