/* inspect the variable major .The variable major should contain only one major for ex:physics or science
.some observations has two majors listed in this variable seperated by the word "and"(always in low case),such as maths and social
. use the word and to identify the a second major and if founf put the second major in a new variable named second_major
.when they are two majors the original major should be modified so that it contains only first major . What is the ffrequency of variable major*/
data subject;
set subjects;
if count(major,'and')>0 then do;
major=tranwrd(major,'and','&');
end;
if count(major,'&')>0 then second_major=scan(major,2,'&');
if count(major,'&')>0 or count(major,'&')=0 then major=scan(strip(major),1,'&');
run;
proc freq data=subject;
table major;
run;
Without seeing the data, it is difficult to say for sure, but for now,
neither the tranwrd nor the scan function will cause an error even if the target is not found, so the following should be fine.
data subject;
set subjects;
major=tranwrd(major,'and','&');
second_major=scan(major,2,'&');
major=scan(major,1,'&');
run;
It is hardly possible to answer the question without seeing the data. But your code has some issues:
1. It is almost always a bad idea to overwrite the dataset being processed.
data subject;
set subjects;
2. No length-statement for the new variable "second_major".
3. Using count will cause unexpected results, because
count("sand", "and") > 0
Using findw is better.
4. Remove
if count(major,'&')>0
and move both assignment statements into the first if-statement.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.