Reputation: 97
that's probably an easy one.
I need to create a variable that is like an order but the order increases only after every second observations.
Thanks in advance!
date order
1-1-10 1
2-1-10 1
3-1-10 2
4-1-10 2
5-1-10 3
6-1-10 3
7-1-10 4
7-1-10 4
etc
Upvotes: 1
Views: 260
Reputation: 12909
You will be using two primary tools: The mod
function and a sum statement. The sum statement looks like incorrect syntax, but it's a special case of retain
.
_N_
is a special variable that acts as your observation counter. Every time that your data
step loops from the top to the bottom (that is, from data
to run
), _N_
increments by one.
By using mod
on _N_
, we can increment a counter by one for every two observations where the result is 1. In other words, if you divide an observation count by 2 and get a remainder of 1, then add 1 to order
.
For example:
_N_ _N_/2 Remainder Operation Value
1 1/2 1 0+1 1
2 2/2 0 N/A 1
3 3/2 1 1+1 2
4 4/2 0 N/A 2
5 5/2 1 2+1 3
6 6/2 0 N/A 3
Ultimately, we are doing an operation where we increment some value at a specific condition, carry it forward, and repeat.
How this code looks:
data want;
set have;
if(mod(_N_, 2) = 1) then order+1;
run;
Upvotes: 3
Reputation: 376
In data step, you can use the automatic variable _n_
, e.g. ceil(_n_/2)
.
In SQL, monotonic()
function can do the same job.
Upvotes: 0