Add a dummy variable to a SAS data set which doesn't depend on existing data

StackOverflow https://stackoverflow.com/questions/23643442

  •  22-07-2023
  •  | 
  •  

Question

I am really having trouble finding the answer to the following simple question. Suppose I have an existing data set with one column of 100 observations, and I want to add a variable which has the value 0 in rows 1-50, and 1 in rows 51-100. How can I do it? I tried:

data new_data;
set existing_data;
 do i = 1 to 100;
  if i <= 50 then new_variable = 0;
  if i >= 51 then new_variable = 1;
 end;
run;

but it doesn't work.

Was it helpful?

Solution

Yep there is a way, use the SAS internal variable _n_ for row number. Like this...

data new;
  set existing;
  if _n_<=50 then new_var=0;
  if _n_>50 then new_var=1;
run;

OTHER TIPS

Well, I figured out one way to do it.

data dummy;
do i = 1 to 50;
  new_variable = 0;
  output;
end;
do i = 1 to 50;
  new_variable = 1;
  output;
end;
run;

data new_data;
  merge existing_data dummy;
run;

Is there a way to do it all in one go?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top