3. Descriptive Statistics: Central Tendency and Dispersion

# 3.5 RStudio Lesson 2: Combining variables and recoding

[Please note: the R Studio Lessons of this book are currently a work-in-progress. Please refer to the SPSS Lessons instead.]

To demonstrate how to recode or reverse code a variable in R, lets download and insert the dataset diamonds in R. As mentioned in the previous section, this dataset is basically regarding the different attributes of diamonds. The variable cut\_new shows the quality of diamond cutting on a score from 1 to 5 where 5 is the best quality. Now let’s assume that we have to reverse the code of this variable to use it in our analysis i.e. we need to recode this variable so that 1 represents the best quality of diamond cutting, 2 represents the second best and so on. We can do this with the help of the function \textit{ifelse}.

diamondscut_new == 5′,1,ifelse(diamondscut_new==3′,3,ifelse(diamondscut_new==`1′,5,NA)))))

The variable cut\_new has now been recoded. You can view the dataset with the revised variable by clicking on the “diamonds” of the data section in the environment tab located in the upper right window. Also you can have a look at the newly recoded variable by telling R to view the first 10 observations of the dataset.