BookmarkSubscribeRSS Feed
GeorgeSAS
Lapis Lazuli | Level 10

Hello all,

 

I have a SAS data set has a variable names 'string' its value looks like:  "a1|a2|a3|a4", "a1|a2",  "a1",   "a1|a2|a3"      (some obs has less '|' and some has more "|") ;

 

I want to create new variables  x1=a1,x2=a2,x3=a3........ but it does not work,

 

please help.

 

Thanks!

Here is my code:

 

data have;

string= "a1|a2|a3|a4"; output;

string= "a1|a2"; output;

string= "a1|a2|a3"; output;

run;

data want;

length x1 x2 x3 x4 x5 $200 ;

set have;

do i=1 to countw(string,"|")

;

/*call symput('x'||left(_i_), scan(string,i,"|"));*/

x%trim(%left(i))=scan(string,i,"|");

end;

run;

5 REPLIES 5
Astounding
PROC Star

You're picturing that macro language can work on DATA step variables, but that's not really the case.  For example, try:

 

%let x = %left(i);

%put *&x*;

 

You'll see that %LEFT is left-hand justifying the character "i", and has nothing to do with the value of a DATA step variable.

 

Try setting up an array:

 

array x {5} $200;

 

Then inside the DO loop you can use:

 

x{i} = scan(string, i, "|");

Loko
Barite | Level 11

Hello,

 

One solution:

 

data want;

length x1 x2 x3 x4 x5 $200 ;

set have;

array x{*} x1 x2 x3 x4 x5;

do i=1 to dim(x) while (missing(scan(string,i,"|"))=0);

x{i}=scan(string,i,"|");

end;

run;

Reeza
Super User

You're in a data step, don't use macro functions. 

 

 

 

Create an array to hold your new variables.

Use the scan function to populate the variables.

Haikuo
Onyx | Level 15

You already have some good answers, below example has been presented many time by @data_null__:

data want;
	infile cards dsd truncover  dlm='|';

	if _n_=1 then
		input @@;
	set have;
	_infile_=string;
	length x1-x5 $200;
	input @1 x1-x5 @@;
	cards;
neccesary evil
;
run;

 

Ksharp
Super User
No. The first I saw this mixed code is Tom, not John King(data _null_) .

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 5 replies
  • 2040 views
  • 2 likes
  • 6 in conversation