BookmarkSubscribeRSS Feed
Vic3
Obsidian | Level 7

Hello,

I want to calculate a new variable "VALUE" based on variables in the same and a previous rows of the dataset and do this by group. This screenshot from Excel makes it self explanatory.

VALUEn = (TIMEn  -  TIMEn-1) * average(RATEn:RATEn-1)

Additional problem is that the calculation has to start from the second row of each group.

I looked at relevant examples on this forum but couldn't make it work.

Thank you.

Vic3_0-1719519258069.png

 

1 REPLY 1
ballardw
Super User

Without data in the from of working data step code or expected results this is untested but may work if your data is sorted by group.

 

data want;
   set have;
   by group;
   diftime= dif(time);
   meanrate= mean(lag(rate),rate);
   if not (first.group) then value=diftime*meanrate;
   drop diftime meanrate;
run;

The DIF function is the difference of the current value of a variable from the previous observation in a data set on the Set statement. Lag returns the value from the previous observation.

Use of a BY statement creates automatic variables First. and Last. that indicate whether the current value is the first or last of a by group. These are numeric values of 1 (True) and 0 (False).

So this calculated the values needed using the current and last observation values of the rate and time but only calculated Value when it isn't the first row of a Group.

 

 

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 1 reply
  • 238 views
  • 0 likes
  • 2 in conversation