The Recode Variables dialog (under the Data menu) allows you to substitute values into existing variables, or create new variables based on current variables.
The following example uses the mtcars data set, which can be loaded by entering
data(mtcars) into the console. Note, this is not an RDS data set, but the process of recoding variables is the same.
To select a variable to recode, simply drag the variable from the variable selection list on the left to the 'variables to recode' list on the right. By default, the recoded variable overwrites the old variable. The 'Target' button allows the saving of the recoded variable to a new variable in the data frame.
cyl variable indicates how many cylinders a car has. We will recode this into a new variable
V8 that will be
1 if the number of cylinders is 8 and
0 otherwise. First we drag cyl to the list on the right, and then click target to specify
V8 as the target variable name.
Clicking the 'Define Recode' button allows us to specify how the recoding should be done.
After clicking on Define Recode, clicking on a recode listed in the top left will show variable information that might be useful to know while doing the recoding. For numeric variables a table of percentiles is shown. For factor and character variables, a table of frequencies is displayed. The 'code' panel allows the specification of the recoding. Note that a value can be recoded to missing by entering
NA into the appropriate field.
Here we wish to recode 8 into 1, and all other values into 0.
This dialog uses the
recode.variables function. The example produces the following call:
mtcars[c("V8")] <- recode.variables(mtcars[c("cyl")] , "8 -> 1;else -> 0;")