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;
data want;
set temp;
if sum(of var1 - var3) eq 0 then var4=1;
else var4=0;
run;
how about this ?
data want;
set temp;
if sum(of var1 - var3) eq 0 then var4=1;
else var4=0;
run;
how about this ?
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"
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.
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.
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;
Try:
var4 = ^sum(of var1-var3);
The ^ produces a Boolean result since any non-zero value is considered true.
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;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.
Find more tutorials on the SAS Users YouTube channel.