Previous: Recoding Variables Up: Recoding Variables Next: Logical Operators

Extracting, Replacing, and Generating New Variables

While it is not difficult to recode variables, the process is prone to human error. Thus, we recommend that before altering the data, you save your existing data frame using the procedures described in Section [*], that you only recode one variable at a time, and that you recode the variable outside the data frame and then return it to the data frame.

To extract the variable you wish to recode, type:

> var <- data$var1               # Copies `var1' from `data', creating `var'.
Do not sort the extracted variable or delete observations from it. If you do, the 4#4 th observation in var will no longer match the 4#4 th observation in data.

To replace the variable or generate a new variable in the data frame, type:

> data$var1 <- var                # Replace `var1' in `data' with `var'.  
> data$new.var <- var             # Generate `new.var' in `data' using `var'.

To remove a variable from a data frame (rather than replacing one variable with another):

> data$var1 <- NULL



Gary King 2011-11-29