Hi SAS Pro,
I have a series Day1-Day3. I want to check during day1-day3 whether people had protein, fiber, and other.
Protein includes: egg cheese pork milk
Fiber: carrot cucumber
Other: all the rest (I don't want to list every item in this category)
In my real dataset, there are many items for each category (i.e. new-created variables), especially in other category, so I would prefer the code that does Not need to list all the items in 'Protein' and 'Fiber' to create 'Other' category. Is there an economical way to write the code?
Have:
ID | Day1 | Day2 | Day3 |
1 | egg | bread | carrot |
2 | cheese | carrot | cucumber |
3 | noodle | cucumber | pork |
4 | bread | pork | pork |
5 | carrot | rice | candy |
6 | cucumber | egg | juice |
7 | pork | cheese | milk |
8 | rice | noodle | |
9 | candy | bread | |
10 | juice | carrot | |
11 | milk |
Want:
ID | Day1 | Day2 | Day3 | Protein Intake=Yes | Fiber Intake=Yes | other than Protein or Fiber Food Intake=Yes |
1 | egg | bread | carrot | 1 | 1 | 1 |
2 | cheese | carrot | cucumber | 1 | 1 | 0 |
3 | noodle | cucumber | pork | 1 | 1 | 1 |
4 | bread | pork | pork | 1 | 0 | 1 |
5 | carrot | rice | candy | 0 | 1 | 1 |
6 | cucumber | egg | juice | 1 | 1 | 1 |
7 | pork | cheese | milk | 1 | 0 | 0 |
8 | rice | noodle | 0 | 0 | 1 | |
9 | candy | bread | 0 | 0 | 1 | |
10 | juice | carrot | 0 | 1 | 1 | |
11 | milk | 1 | 0 | 0 |
Thank you very much!
Kind regards,
C
Continue to the previous post
If there is missing in day1-day3, then other=0.
Thank you again!
C
Hi @CynthiaWei
Here is an attempt to do this using arrays:
data have;
infile datalines dlm="09"x truncover;
input ID Day1 :$20. Day2 :$20. Day3 :$20.;
datalines;
1 egg bread carrot
2 cheese carrot cucumber
3 noodle cucumber pork
4 bread pork pork
5 carrot rice candy
6 cucumber egg juice
7 pork cheese milk
8 rice noodle
9 candy bread
10 juice carrot
11 milk
;
run;
%let protein = "egg" "cheese" "pork" "milk";
%let fiber = "carrot" "cucumber";
data want;
set have;
array Day(*) Day1-Day3;
Protein_Intake_Y=0;
Fiber_Intake_Y=0;
Other_Intake_Y=0;
do i=1 to dim(Day);
if day(i) in (&protein) then Protein_intake_Y=1;
if day(i) in (&fiber) then Fiber_intake_Y=1;
if day(i) not in ("" &protein &fiber) then Other_intake_Y=1;
end;
drop i;
run;
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9.
Early bird rate extended! Save $200 when you sign up by March 31.
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.