LAG can work. Assuming DTALT is a numeric value with a european style data format.
[pre]
proc sort data=indata;
by codfonte codtit dtalt;
run;
data outdata;
set indata;
by codfonte codtit;
if first.codtit then lag(valor);
diff = valor - lag(valor);
if not first.codtit then output;
run;
[/pre]
Does this help?
Lag does not mean "use the previous value", like you would hope it does.
The "LAG" documentation is a little confusing and easily mis-interpreted. I had to spend a couple hours/days experimenting until I fully understood what was happening.
LAG simply represents a FIF0 queue of some depth: lag = lag1 = depth of 2; lag10 = depth of 11 (could be 1 and 10 for the actual implementation, but this is easier to explain). When the function is called, it loads the current value at the variable into a queue for that variable and then retrieves the last value in the queue and returns that value. So, the first time LAG(valor) is used/called, it loads the value of VALOR into the queue and then returns a missing value. The next time LAG(valor) is executed, a new value is put into the queue (now holding 2 actual meaningful values) and then retrieves the end/last/previous value and returns that value for use. This is why it is easy to trip over the use of LAG within conditional statements, because it does not necessarily have the value from the previous observation if the conditional was different for that observation. This is also why you have to be careful with the number of times LAG is used with a particular variable in a datastep. If it is desired that the lag variable explicitly mean "previous observation value" then use:
[pre]
prior_value = lag(value);
[/pre]
in the code to hold that prior value for use
[pre]
diff1 = value - lag(value);
value3 = value2*lag(value);
[/pre]
is very different from
[pre]
prior = lag(value);
diff1 = value - prior;
value3 = value2 * prior;
[/pre]