If you find any of this useful, please consider donating via PayPal to help keep this site going.

Email news@statisticool.com to sign up to receive news and updates

Swapping Variables


When you work with data, it is often necessary to edit it. In this article, I show some simple pseudo-code to swap data between variables. This will be done without the typically used step of creating a temporary third variable used to move the data around.

Say on a survey form there is a START and an END box that the respondent fills out, but the respondent mixes them up and puts the start in the END box and the end in the START box. How would you recognize and fix this situation?

Here is my solution:

if end lt start then do;

end = end+start;

start = end-start;

end = end-start;


For example, let's walk through what the code is doing with end=2013 and start=2016. My comments will be in parentheses.

if end lt start (this is true, end is less than start) then do;

end = end+start; (so end = 4029, start = 2016)

start = end-start; (now end = 4029, start = 2013)

end = end-start; (and last, end = 2016, start = 2013)

We have successfully swapped the start and end data that were provided to us incorrectly. I've used this code in a SAS program, and it seems to work with numeric as well as character dates.

Please anonymously VOTE on the content you have just read:


If you enjoyed any of my content, please consider supporting it in a variety of ways:

AFFILIATE LINK DISCLOSURE: Some links included on this page may be affiliate links. If you purchase a product or service with the affiliate link provided I may receive a small commission (at no additional charge to you). Thank you for the support!