## Creation of a New Variable

Super Contributor
Posts: 338

# Creation of a New Variable

Hello colleagues,
I have over 10,000 data set related to Material Deprivation like this .

Data MD;
Input ID Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 Q9 Q10; /*ID=Household ID*/
cards;
1 2 2 1 1 7 8 9 1 1 9
2 2 2 2 1 1 1 1 7 8 9
3 7 8 9 7 8 9 7 8 9 2
4 1 1 1 1 1 1 1 1 1 1
;
Run;

Note: Responses 7, 8, and 9 are don’t know, refusal and not stated respectively.

I need to create a new variable called deprived where deprived=1 if you get two or more ‘2’ s for a given household across variables Q1 to Q10, else deprived =2

For instance, the new variable deprived for these four households should get following values:

For first household, deprived =1 (because there are two ‘2’ s)
For second household, deprived =1 (because there are three ‘2’ s)
For third household, deprived =2 (because there is only one ‘2’ )
For third household, deprived =2 (because there are no “two or more ‘2’ s”)

Thanks

Neil
Posts: 3,852

## Re: Creation of a New Variable

[pre]
deprived = ifN(lengthN(compress(cats(of q,'2','K')) ge 2,1,2);
[/pre]
Super Contributor
Posts: 338

## Re: Creation of a New Variable

Many thanks for this code which works nicely.

Neil
Super User
Posts: 10,787

## Re: Creation of a New Variable

My idea is :

data new;
set md;
index=1*(Q1=2)+1*(Q2=2)+1*(Q3=2)+1*(Q4=2)+1*(Q5=2)+1*(Q6=2)+1*(Q7=2)+1*(Q8=2)+1*(Q9=2)+1*(Q10=2);
if index ge 2 then deprived=1;
else deprived=2;
drop index;
run; Message was edited by: Ksharp
Valued Guide
Posts: 2,191

## Re: Creation of a New Variable

Mirisage

For brevity, consider [pre]
deprived = 2-( count( cats(of q1-q10), '2' ) >1 ) ;
[/pre]
the count() function will return the number of '2' in the concatenation of Q1-Q10 .
The logical test {that count} >1 returns 1 when there are 2 or more 2s, and 0 otherwise.
Super Contributor
Posts: 338

## Re: Creation of a New Variable

Hi Ksharp & Peter,

Thank both of you. These different approaches are very helpful. And Peter's accompanying text is very helpful.

Thanks

Neil
Discussion stats
• 5 replies
• 167 views
• 0 likes
• 4 in conversation