## How to creat a new variable in this condition?

Solved
Frequent Contributor
Posts: 75

# How to creat a new variable in this condition?

The data looks like this

data temp;

input var1 var2 var3;

datalines;

1 1 0

0 0 0

0 1 0

1 1 1

;

There are a few observations with all 0s, how can I efficiently create a new dichotomous variable (e.g., var4) which assigns 1 to those observations and 0 otherwise? The output may look like:

1 1 0 0

0 0 0 1

0 1 0 0

1 1 1 0

This should work but it looks unattractive:

data want; set temp;

var4 = 0;

if var1 = 0 and var2 = 0 and var3 = 0 then var4 = 1;

run;

Btw, will this work?

data want; set temp;

var4 = 0;

array abc var1 var2 var3;

do i = 1 to 3;

if abc(i) = 0 then  var4 = 1;

end; run;

Accepted Solutions
Solution
‎07-22-2015 02:55 AM
Contributor
Posts: 27

## Re: How to creat a new variable in this condition?

data want;

set temp;

if sum(of var1 - var3) eq 0 then var4=1;

else var4=0;

run;

All Replies
Solution
‎07-22-2015 02:55 AM
Contributor
Posts: 27

## Re: How to creat a new variable in this condition?

data want;

set temp;

if sum(of var1 - var3) eq 0 then var4=1;

else var4=0;

run;

Frequent Contributor
Posts: 75

## Re: How to creat a new variable in this condition?

This is a working solution for this one. But what will it be on a more general issue? I mean, for example, let's say that for variables var1 to var3, value "1" is now "NYC" and "0" is now "Buffalo"

Frequent Contributor
Posts: 88

## Re: How to creat a new variable in this condition?

Maybe this:

var4 = ^(var1=var2=var3);

Sorry - missed the point.  You want something like:

var4 = (var1=var2=var3 ='Buffalo');

Your array processing would be fine too of course, and more generic.

Frequent Contributor
Posts: 75

## Re: How to creat a new variable in this condition?

I was a bit suspicious over my array, because it seems to me the array will assigns 1 if any, but not ALL, of these variables (var1 var2 var3) is 0.

Super User
Posts: 9,441

## Re: How to creat a new variable in this condition?

Then you would need to count the words or replace:

array var{3};

if countw(catx(',',of var{*}),"NYC") > 0 then var4=1;  /* i.e. if NYC exists in the string then the result is 1 */

else var4=0;

Frequent Contributor
Posts: 88

## Re: How to creat a new variable in this condition?

Try:

var4 = ^sum(of var1-var3);

The ^ produces a Boolean result since any non-zero value is considered true.

Contributor
Posts: 74

## Re: How to creat a new variable in this condition?

data Want;

set Have;

count = 0;

array ary(*) var1-var3;

do i = 1 to dim(ary);

if ary(i) = 0 then count+1;

end;

if count = 3 then var4=1;else var4= 0;

drop count i;

run;

🔒 This topic is solved and locked.