BookmarkSubscribeRSS Feed
Bluejags
Obsidian | Level 7

I have a data that looks lie this:

 

Pat_ID City Sex 

012   1      

012  1     M

012 1     

015  2    F

015 2

016 1    M

016 1

 

I need to fill in the gender in the last column using the info available.  I am new and would appreciate any help.  The RETAIN statement works for PAT_ID 015 and 016 but not for the 012, as the sex info is missing in the first row.

6 REPLIES 6
Reeza
Super User

SQL is easiest here, as it allows for summary and row level calculations in a single code block - it still does the extra steps behind the scenes.

 

proc sql;
create table want as
select pat_id, city, coalesce(sex, max(sex)) as sex
from have
group by pat_id
order by 1, 2;
quit;

Otherwise something like this may work as well:

 

data gender;
set have;
where not missing(sex);
by pat_id;
if first.pat_id;
run;

data want;
merge have gender (rename=sex = sex_found);
by pat_id;
sex = coalescec(sex, sex_found);
run;

@Bluejags wrote:

I have a data that looks lie this:

 

Pat_ID City Sex 

012   1      

012  1     M

012 1     

015  2    F

015 2

016 1    M

016 1

 

I need to fill in the gender in the last column using the info available.  I am new and would appreciate any help.  The RETAIN statement works for PAT_ID 015 and 016 but not for the 012, as the sex info is missing in the first row.


 

Bluejags
Obsidian | Level 7

Hi Reeza, the codes didnt work.  Still getting blank cells for gender.

Ksharp
Super User
data have;
infile cards truncover;
input Pat_ID City Sex $;
cards;
012   1      
012  1     M
012 1     
015  2    F
015 2
016 1    M
016 1
;

data want;
 merge have have(where=(new_sex is not missing) rename=(sex=new_sex));
 by Pat_ID City;
run;
Bluejags
Obsidian | Level 7

Hi Ksharp,

The code did not work.  Here is the output.  Still the sex is missing from row. The log did not indicate any errors though. Am i doing something wrong?

jagscbe_0-1635258578858.png

 

 

 

Reeza
Super User

That's a screenshot of your HAVE data set not the newly created data set, WANT. Check your output again please.

EDIT: I just tested all three solutions posted (2 of mine and @Ksharp) all work as expected on the posted sample data.

 

Bluejags
Obsidian | Level 7

MY BAD. Thanks Reeza for pointing out that i was not looking into the WANT and only the HAVE.  I am new to SAS  and didn't realize the output screen has option to click to look into all files generated for the set of codes.  

 

Also thanks to @Ksharp too. 

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 6 replies
  • 1758 views
  • 0 likes
  • 3 in conversation