Swap a portion of data between columns

Reply
Regular Contributor
Posts: 212

Swap a portion of data between columns

Here's one that Excel can do, so I'll use Excel if no fairly easy SAS way is possible.

Note following portion of data set:

ComboVar_1Var_2
20101_216030.-1.94930
20101_216030.-1.80663
20101_216030.-1.66396
20101_216030.-1.52129
21603_20101-0.807940.
21603_20101-0.665270.
21603_20101-0.522600.
21603_20101-0.379930.

Focus only on the Var_1 and Var_2 columns..., at least for the time being.

I need to "swap" the contents of the bottom four rows of cells.

Does SAS have a way to do this -- without your having to write tons of code?

Thanks much.

Nicholas Kormanik

Super Contributor
Posts: 644

Re: Swap a portion of data between columns

There is no data step swap function (I've occasionally wished for it) but you can temporarily create another column say temp, then use code such as

If (condition to select rows to swap)

  then do ;

temp = Var_1 ;

Var_1 = Var2 ;

Var_2 = temp ;

end ;

drop temp ;

You can also do it in sql, without creating a temp column but it is a lot more verbose.

Richard

Super User
Posts: 5,257

Re: Swap a portion of data between columns

Unclear where you write the line for tons Smiley Wink, but here goes (assuming that you need to store column with values <> 0 in one column):

proc sql;

     update mytable

          set var_2 = var_1

          where var_1 <> 0 and var_2 = 0

     ;

quit;

Comparing to Excel is puzzling me. Excel is great when doing minor ad-hoc stuff, SAS is suited for developing programs that can be used multiple times, in batch etc.

Data never sleeps
Ask a Question
Discussion stats
  • 2 replies
  • 160 views
  • 0 likes
  • 3 in conversation