Title

swapval -- Swapping values of two variables

Syntax

swapval avar bvar [if] [in]

Description

swapval interchanges the values of two variables avar and bvar,
so long as both variables are numeric or both are string.

Remarks

swapval may be useful whenever data checking suggests that values for two
variables have been interchanged. In simple cases, this calls for a few
replace statements, or the use of the data Editor, but in other cases
a single command may be useful.

swapval can be applied unconditionally, in which case it is in essence
a swapping of variable names.

Alternatively, it can be applied conditionally, using if and/or in,

Examples

In a data set max should always be not less than min.
A check shows that this is not true in two observations,
42 and 666. If we suppose that this must be a data error,
then it can be fixed by

. swapval min max if inlist(_n, 42, 666)

or

. swapval min max if max < min

See also rowsort (Cox 2009).

Author

Nicholas J. Cox, University of Durham, U.K.

n.j.cox@durham.ac.uk

Acknowledgments

This command was first issued in 1999.
In 2025 Daniel Klein identified a bug and commented on a rewriting of the code.
The opportunity has been taken to simplify the design of the command.

Reference

Cox, N. J. 2009. Speaking Stata: Rowwise. Stata Journal 9: 137-157.

Also see

On-line: help for replace, edit, rowsort (if installed)