LISTSERV at the University of Georgia
Menubar Imagemap
Home Browse Manage Request Manuals Register
Previous messageNext messagePrevious in topicNext in topicPrevious by same authorNext by same authorPrevious page (November 2004, week 5)Back to main SAS-L pageJoin or leave SAS-L (or change settings)ReplyPost a new messageSearchProportional fontNon-proportional font
Date:   Mon, 29 Nov 2004 11:07:28 -0500
Reply-To:   Venky Chakravarthy <venky.chakravarthy@PFIZER.COM>
Sender:   "SAS(r) Discussion" <SAS-L@LISTSERV.UGA.EDU>
From:   Venky Chakravarthy <venky.chakravarthy@PFIZER.COM>
Subject:   Re: New variable at previous time

Here is another approach. Take advantage of the natural RETAIN of variables coming from an input data set.

data sales1 ; input Date : date7. monyr $ Prod $ Sales Sales_1 ; cards ; 01jan04 jan04 prod1 100 . 01feb04 feb04 prod1 90 100 01mar04 mar04 prod1 70 90 run ;

data new1 ; previous_sale = sales ; set sales1 ; run ;

It is possible do this even when you have BY GROUP variables and need to reset the previous sale value when crossing boundaries. Note that the LAST.VAR is used in place of FIRST.VAR to reset the previous sale value to missing. We are once again taking advantage of the natural retain on LAST.VAR at the next iteration of the data step. Consider

data sales2 ; input Date : date7. monyr $ Prod $ Sales Sales_1 ; cards ; 01jan04 jan04 prod1 100 . 31jan04 jan04 prod1 100 100 01feb04 feb04 prod1 90 . 15feb04 feb04 prod1 90 90 01mar04 mar04 prod1 70 . 12mar04 mar04 prod1 70 70 run ;

data new2 ; if last.monyr then previous_sale = . ; else previous_sale = sales ; set sales2 ; by monyr notsorted ; run ;

Not to be outdone, the DOW begs the case for the BY GROUP processing as well. However, care must be taken to place the OUTPUT statement in the right place.

data new3 ; do until (last.monyr) ; set sales2 ; by monyr notsorted ; output ; previous_sale = sales ; end ; run ;

Venky Chakravarthy

On Mon, 29 Nov 2004 12:30:14 +0100, LWn <Lars.WahlgrenRemove@THIS.STAT.LU.SE> wrote:

>You can use the lag-function > >data new ; > set old ; > previous_sales = lag1(sales) ; >run ; > >HTH / LWn > >"paul" <p.stat@tiscali.it> skrev i meddelandet >news:ea197b2e.0411290307.eeef2ee@posting.google.com... >> Hi >> I have a dataset with 3 columns: Date (month), Products and Sales. >> I wonder if I could set a new variable in the same dataset: "Sales at >> previous >> time". I don't be able to do that. >> Example >> >> Date---Prod---Sales---Sales(-1) >> jan04--prod1--100-----. >> feb04--prod1--90------100 >> mar04--prod1--70------90 >> >> Could you help me? >> >> Thanks >> Paul


Back to: Top of message | Previous page | Main SAS-L page