BookmarkSubscribeRSS Feed
Junyong
Pyrite | Level 9

Can I insert a new variable in a specific position? For example, the following working data set is ordered already and contains some numbers.

data _(drop=i);
	array x(*) us uk france germany poland spain italy ireland sweden denmark norway finland china japan korea iran iraq turkey india brazil singapore mexico;
	do i=1 to dim(x);
		x(i)=rannor(1);
	end;
run;

If I use the following code, then the new variable greece will be located at the end of the data set.

data _;
	set _;
	greece=rannor(1);
run;

I wonder whether the position can be changed—for example, in between the existing variables italy and ireland. Thanks in advance.

2 REPLIES 2
Astounding
PROC Star

You can do this in a few ways.  Given that you already have an ARRAY statement, the easiest way would be to repeat the ARRAY statement in the second DATA step (with GREECE added in the proper position).  Place the revised ARRAY statement between the DATA statement and the SET statement.

ballardw
Super User

I will say that I have never bothered to worry about the order of variables in a data set. I don't read data sets. Computer code reads data sets and generally doesn't care. I read reports. And I can control the output in the report to get what I need at that point instead of worrying about changes elsewhere.

 

Note that code you wrote to process the original data set could have notable issues if you use the variable Greece where the previous value was for a different variable because of array processing.

 

For a large number of processes you would likely be ahead to have a transposed data set where you have a variable named COUNTRY that has values like US UK Germany Greece etc. Then you can easily process each country without having to pick it out of a row of similar values.

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
  • 2 replies
  • 822 views
  • 0 likes
  • 3 in conversation