DATA Step, Macro, Functions and more

How to assign a column value based on another column ??

Accepted Solution Solved
Reply
Occasional Contributor
Posts: 19
Accepted Solution

How to assign a column value based on another column ??

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


Accepted Solutions
Solution
‎04-08-2015 02:53 PM
Valued Guide
Posts: 858

Re: How to assign a column value based on another column ??

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;

View solution in original post


All Replies
Valued Guide
Posts: 858

Re: How to assign a column value based on another column ??

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;

Occasional Contributor
Posts: 19

Re: How to assign a column value based on another column ??

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

Solution
‎04-08-2015 02:53 PM
Valued Guide
Posts: 858

Re: How to assign a column value based on another column ??

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;

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 3 replies
  • 584 views
  • 3 likes
  • 2 in conversation