DATA Step, Macro, Functions and more

Create variables dynamically

Accepted Solution Solved
Reply
Contributor
Posts: 63
Accepted Solution

Create variables dynamically

Hi All;

 

Below is the data i have.

 

data have;
 input idvar subj ;
 datalines;
 1 101
 2 102
 3 103
 4 105
 5 106
 6 107
 7 111
 8 112
 ;

I want to create new 4 variables as subj1 , subj2 ,subj3,subj4 containing two records each and new dataset contain only subj values not idvar values.

 

Can you please guide how can i keep it dynamic as next time  i do not need to check record count and new variable created automatically by sas program ?


Accepted Solutions
Solution
Thursday
Super User
Posts: 9,868

Re: Create variables dynamically

Try this:

data have;
input idvar subj ;
datalines;
1 101
2 102
3 103
4 105
5 106
6 107
7 111
8 112
;
run;

data int;
set have;
retain group 0;
if mod(idvar,4) = 1 then group + 1;
idvar = mod(idvar - 1,4) + 1;
run;

proc transpose
  data=int
  out=want (drop=group _name_)
  prefix=subj
;
by group;
var subj;
id idvar;
run;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code

View solution in original post


All Replies
Solution
Thursday
Super User
Posts: 9,868

Re: Create variables dynamically

Try this:

data have;
input idvar subj ;
datalines;
1 101
2 102
3 103
4 105
5 106
6 107
7 111
8 112
;
run;

data int;
set have;
retain group 0;
if mod(idvar,4) = 1 then group + 1;
idvar = mod(idvar - 1,4) + 1;
run;

proc transpose
  data=int
  out=want (drop=group _name_)
  prefix=subj
;
by group;
var subj;
id idvar;
run;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Super User
Super User
Posts: 9,397

Re: Create variables dynamically

Show some example output.  From what you post it sounds like you want to tranpose the data to something like:
subj101 subj102 subj103...

 

For this use the proc transpose function, however I would also recommend not to work with transposed data as it increases the amount of code you will need to write to work with it.

 

As for "

and new dataset contain only subj values not idvar values.

 "

What does this mean?  Examples really help!

Maybe:

data want;
  set have (keep=subj);
run;

/* Or if from the transposed */
data want;
  set have (keep=subj:);
run;

/* Note the colon, meaning anything with prefix */
☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 2 replies
  • 73 views
  • 0 likes
  • 3 in conversation