Help using Base SAS procedures

New Variable combining several codes

Reply
Super Contributor
Posts: 338

New Variable combining several codes

Hi Colleagues,

Would appreciate if anyone of you could help on this.

I have 7000 observations like this.


data Family;
input ID Family_type;
cards;
1 1
2 1
3 1
4 2
5 3
6 4
7 6
8 5
9 6
10 4
;
run;

I need to create a new variable called ‘Type’ using the existing variable ‘Family_type’.

Condition is:
If Family_type = 2 or 3 or 4, Type = 4
All other codes of ‘Family_type’ variable should remain the same for newly created ‘Type’ variable too.

I tried the following but did not work.

data Family_1;
set Family;
if Family_type = 2 or Family_type = 3 or Family_type = 4 then Type = 4 ;
if Family_type = 1 then Type = 1;
if Family_type = 5 then Type = 5;
else Type = 6;
run;

I would appreciate if you could help me.
Thank you

Mirisage
Super Contributor
Posts: 259

Re: New Variable combining several codes

The problem is your last if/else code:
[pre]
if Family_type = 5 then Type = 5;
else Type = 6;
[/pre]
The else-part sets Type = 6 if Family_type != 5. Try following untested code skips checking the value of Family_type if Type equals Family_type.
[pre]
data Family_1;
set Family;
if Family_type = 2 or Family_type = 3 or Family_type = 4 then Type = 4;
else Type = Family_type;
run;[/pre]
The if-statement can be made easier to understand by using the in-operator:
[pre]...
if Family_type in (2, 3) then Type = 4;
else Type = Family_type;
...[/pre]
Super Contributor
Super Contributor
Posts: 3,174

Re: New Variable combining several codes

Check for missing "ELSE" operator in some of your IF / THEN statements.

A useful debugging technique when desk-checking your program is to insert the statement below which will generate additional diagnostic information (about variable values) along the course of your DATA step (increment "nn" below when you have multiple of these lines in your program for identification):

PUTLOG '>DIAG-nn>' / _ALL_;

Scott Barry
SBBWorks, Inc.
Contributor
Posts: 66

Re: New Variable combining several codes

Try this.

data Family_1;
set Family;
if Family_type=2 or Family_type=3 or Family_type=4 then Type=4 ;
if Family_type= 1 then Type=1;
if Family_type= 5 then Type=5;
if type=. then type=Family_type;
run;
Super Contributor
Posts: 338

Re: New Variable combining several codes

Hi andreas_lds, sas_ and sbb,

Thank all of you. All the codes suggested by you all worked quite well.

Regards

Mirisage
Frequent Contributor
Posts: 75

Re: New Variable combining several codes

DATA FAMILY_1;
SET FAMILY;
IF Family_type IN (2,3,4) THEN TYPE=4;
ELSE TYPE=Family_type;
RUN;
Ask a Question
Discussion stats
  • 5 replies
  • 138 views
  • 0 likes
  • 5 in conversation