BookmarkSubscribeRSS Feed
SAS_Practice
Calcite | Level 5

I have a following data-set (Given)     with a character variable "var1". Need to create a numeric variable "var2" where the numbering will be same pattern as the (WANT) dataset ( find it on the bottom of this post). the values of "var2" changes when there is no space in-front of the value of "var1". If there is space in-front of the value of :var1" then "var2" keeps the value from the previous iteration.

GIVEN:

 

 

var1

---------------

subject died

subject alive

     struggling

     sick

In Vacation

Never lived 

     Gone for good

Never showed up

 

The WANT dataset should be as below, 

 

var1                                    var2

----------------------             ---------------------

subject died                     10

subject alive                     20

     struggling                    20

     sick                             20

In Vacation                       30

Never lived                      40

     Gone for good            40

Never showed up            50

 

 

Thank you so much.

 

7 REPLIES 7
Reeza
Super User
Indents are fun.
Use SUBSTR() to check the first character of the string. If it's a space you don't increment your counter, otherwise increment your counter.

data want;
set have;
retain var2 10;
if substr(var1, 1,1) = " " then var2+10;
run;
novinosrin
Tourmaline | Level 20

Hello @SAS_Practice  I like SCAN

 

data have;
input var  $char50.;
cards;
subject died
subject alive
     struggling
     sick
In Vacation
Never lived 
     Gone for good
Never showed up
;

data want;
set have;
if scan(var,1,' ','m')>' ' then var2+10;
run;
data_null__
Jade | Level 19

 

FIRST function?

 

if not missing(first(var)) then var2+10;
novinosrin
Tourmaline | Level 20

Guru @data_null__   That's a great teaser. Well done! 🙂

 

A similar teaser to @Reeza   , char beats substr in golf lol

 

if char(var,1)>' ' then var2+10;

 

 

Astounding
PROC Star

How about no functions at all?

 

if var1 >: ' ' then var2 + 10;
novinosrin
Tourmaline | Level 20

@Astounding  Wow. Winner by a mile! Kudos!!!!!!!!

Ksharp
Super User

Here is one more way.

 

if var not =: ' ' then var2+10;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

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
  • 7 replies
  • 1635 views
  • 8 likes
  • 6 in conversation