Email news@statisticool.com to sign up to receive news and updates
Swapping Variables
3/2/16
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;
end;
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:
Like:Dislike:
If you enjoyed any of my content, please consider supporting it in a variety of ways:
- PLEASE take a moment to check out two GoFundMe fundraisers I set up. The idea is to make it possible for me to pursue my passions. My goal is to be able to create free randomized educational worksheets and create poetry on a full-time basis. THANK YOU for your support!
- Email news@statisticool.com to sign up to receive news and updates
- Donate any amount via PayPal
- Take my Five Poem Challenge
- Subscribe to my YouTube channel
- Visit my Amazon author page
- Buy what you need on Amazon using my affiliate link
- Follow me on Twitter here
- Buy ad space on Statisticool.com
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!