BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
jeniffer_jacob
Fluorite | Level 6

I tried to assign 2 different values (1, 0) of a new variable according to the value of an existing variable.

data test2;

set test;

if target in ("rain", "snow") then target_kgb = "1";

else if target = "sunny" then target_kgb = "0";

run;

 

But I can only assign 1 to target_kgb if target in rain or snow. 0 was not assigned to target_kgb even though there were many "sunny" for target.

 

Any help is highly appreciated.

 

Thank a lot.

1 ACCEPTED SOLUTION

Accepted Solutions
Astounding
PROC Star

Your code is perfect.  Most likely, the data are a little bit different.  For example, none of these would produce a match with "sunny":

 

Sunny

s u n n y

suny

SUNNY

    sunny

 

Character strings must match exactly.

View solution in original post

4 REPLIES 4
jklaverstijn
Rhodochrosite | Level 12

Check the length of your variable "target". Without anything else it will be defined as $4 because "rain" is the first possible value the datastep finds. it is safer to add a statement

 

length target $5;

before the if-then-else statements. This will prevent "sunny" to be truncated to "sunn" which never matches "sunny". Possibly this is already happening in the creation of dataset test. We would need to see more of your program and logs to know for sure. Do a proc contents on dataset test.

 

Hope this helps,

-- Jan

Astounding
PROC Star

Your code is perfect.  Most likely, the data are a little bit different.  For example, none of these would produce a match with "sunny":

 

Sunny

s u n n y

suny

SUNNY

    sunny

 

Character strings must match exactly.

Amir
PROC Star

Hi,

 

Your data step code worked OK for me when I tried the following data:

 

 

data test;
   input target $8.;
   datalines;
rain
snow
sunny
;

data test2;
   set test;
   if target in ("rain", "snow") then target_kgb = "1";
   else if target = "sunny" then target_kgb = "0";
run;

 

 

Perhaps you have a leading space(s) before "sunny" in the variable target, in which case you could try using:

 

else if left(target) = "sunny" then target_kgb = "0";

 

If that works then I recommend you use left(target) wherever you have target.

 

 

Regards,

Amir.

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

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
  • 1129 views
  • 0 likes
  • 4 in conversation