HI Guys,
I have a question about data step. if I have a table with two columns, Type and value. What I am trying to do is for all the same type group records, their values will be assigned the smallest value in this group.
data tao;
input type $ Mvalue ;
datalines;
A 12
B 15
C 18
C 19
D 23
E 11
E 90
E 100
;
run;
So the Result I want to see is
A 12
B 15
C 18
C 18
D 23
E 11
E 11
E 11
I can easily find those records need to be changed but not sure how to assign the smallest value in the group. However, I tried several ways to do this and it does not work because lag function always grab the one in the lag queue. For example, code below will not work.
data YYY;
set tao;
if type=lag(type) then mvalue=lag(mvalue);
run;
I can also use last.type to find the records, but not sure how to assign the values;
Hope someone can give me some hints.
Thanks,
Tao
This will get you the same thing in a datastep:
data tao_want;
set tao;
retain m_value;
by type;
if first.type then m_value = value;
if m_value > value then m_value = value;
run;
You can use the min() with sql:
proc sql;
create table want as
select *,min(Mvalue) as min_Mvalue
from have
group by type
order by type;
Hi Mark,
Thank you for your reply! Your solution definitely works! However, I wonder if there is a way in data step can do the same thing? I believe there should be but I just cannot figure it out. If it is not easy to do in data step, then in the future for this kind of issue, I probably will keep using proc sql way.
Tao
This will get you the same thing in a datastep:
data tao_want;
set tao;
retain m_value;
by type;
if first.type then m_value = value;
if m_value > value then m_value = value;
run;
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.