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.
If you enjoyed any of my content, please consider supporting it in a variety of ways: