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-white.png

Special offer for SAS Communities members

Save $250 on SAS Innovate and get a free advance copy of the new SAS For Dummies book! Use the code "SASforDummies" to register. Don't miss out, May 6-9, in Orlando, Florida.

 

View the full agenda.

Register now!

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

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