BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
Feyng819
Obsidian | Level 7
For example I have the data:
data have;
input name$;
cards;
Aaron Smith Andrew Knoi
Linda Jackson Betty Young
;
run;

I want to create separate rows based on the second space like the data in the following.
data want;
input name$;
cards;
Aaron Smith
Andrew Knoi
Linda Jackson
Betty Young
;
run;

How can create separate rows based on the second space? I tried to use scan but it seems to be only working for the first space. Thank you!
1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

Loop through the string, incrementing the loop counter by 2:

data have;
input name $80.;
cards;
Aaron Smith Andrew Knoi
Linda Jackson Betty Young
;

data want;
set have;
i = 1;
word = scan(name,i);
do while(word ne "");
  n_name = catx(" ",scan(name,i),scan(name,i+1));
  output;
  i = i + 2;
  word = scan(name,i);
end;
keep n_name;
rename n_name=name;
run;

View solution in original post

5 REPLIES 5
Kurt_Bremser
Super User

Loop through the string, incrementing the loop counter by 2:

data have;
input name $80.;
cards;
Aaron Smith Andrew Knoi
Linda Jackson Betty Young
;

data want;
set have;
i = 1;
word = scan(name,i);
do while(word ne "");
  n_name = catx(" ",scan(name,i),scan(name,i+1));
  output;
  i = i + 2;
  word = scan(name,i);
end;
keep n_name;
rename n_name=name;
run;
Feyng819
Obsidian | Level 7
This works great! Thank you
Astounding
PROC Star

It's actually easier if you create two variables instead of one:

data have;
  length first_name last_name $ 20;
  input first_name last_name @@;
cards;
Aaron Smith Andrew Knoi
Linda Jackson Betty Young
;
andreas_lds
Jade | Level 19

Can you add an example showing what should happen if the value has to separated at the third space?

Ksharp
Super User
data have;
input name $40.;
cards;
Aaron Smith Andrew Knoi
Linda Jackson Betty Young
;
run;

data want;
 set have;
 call scan(name,2,p,l,' ');
 new_name=left(substr(name,1,p+l));output;
 new_name=left(substr(name,p+l));output;
 drop p l;
run;

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

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
  • 5 replies
  • 566 views
  • 1 like
  • 5 in conversation