BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Emma_at_SAS
Lapis Lazuli | Level 10

Hello,

I want to create a column (column_3) based on two other columns (column_1 and column_2).

  • if both column_1 and column_2 have a value then column_3 is the average of column_1 and column_2
  • If the values for either column_1 or column_2 are missing (only one of them has a value) then column_3 is set equal to the non-missing value.

I know my code is wrong, but something like this

data want;
set have;
column_3=.;
if column_1 eq '.' and column_2>0 then column_3=column_2;
if column_2 eq '.' and column_1 >0 then column_3=column_1;
else if column_1>0 and column_2>0 then column_3 = (column_1+column_2)/2;

run;

 

Thanks

1 ACCEPTED SOLUTION

Accepted Solutions
andreas_lds
Jade | Level 19

Assuming that the variables are numeric, you just compare with . not enclosed in quotes. But in your task, you don't have to use if at all. The function mean takes care of missing values:

data havewant;
   input col1 col2;
   
   col3 = mean(col1, col2);
   
   datalines;   
5 .
. 7
4 6
;

View solution in original post

4 REPLIES 4
andreas_lds
Jade | Level 19

Assuming that the variables are numeric, you just compare with . not enclosed in quotes. But in your task, you don't have to use if at all. The function mean takes care of missing values:

data havewant;
   input col1 col2;
   
   col3 = mean(col1, col2);
   
   datalines;   
5 .
. 7
4 6
;
Emma_at_SAS
Lapis Lazuli | Level 10

Thank you, andreas! Great and easy solution!
Reeza
Super User
The MEAN() function does that automatically so you don't need to do any manual checks.
If dealing with missing values, another function that's often used is COALESCE(), which takes the first non missing values from a list of variables.

Emma_at_SAS
Lapis Lazuli | Level 10
Thanks, Reeza. Good to know.

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

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
  • 4 replies
  • 802 views
  • 5 likes
  • 3 in conversation