

His company, Sigma Statistics and Research Limited, provides both on-line instruction and face-to-face workshops on R, and coding services in R. To see more of the R is Not So Hard! tutorial series, visit our R Resource page.Ībout the Author: David Lillis has taught R to many researchers and statisticians. The general approach is the same as before, but now you have a few additional sets of parentheses. We can recode back to character just as easily.

We now use nested ifelse commands to re-code Orcs as 1, Elves as 2, Hobbits as 3, and Trolls as 4. The sets where Peter Jackson produced these films are just a short walk from where I live, so the example is relevant for me.

My last example is drawn from the films of the Lord of the Rings and the Hobbit.
#Rcode values in r in order code
You can use the same approach to code as many different levels as you need to. Note that the Gender variable is located in the first column, or A.Ī <- ifelse(A = "M", 1, ifelse(A = "F", 2, 99)) We have deliberately introduced an error where gender is misclassified as B. The element with unknown gender was re-coded as 3. Ifelse(gender = "MALE", 1, ifelse(gender = "FEMALE", 2, 3)) It involves repeated (nested) use of the ifelse() command. Very useful is the following re-coding syntax because it works in many practical situations. Let’s re-code males as 1 and females as 2. "MALE" "FEMALE" "FEMALE" "UNKNOWN" "MALE" In such cases, you might want to re-code an array with character elements to numeric elements. However, some re-coding tasks are more complex, particularly when you wish to re-code a categorical variable or factor. Let’s re-code all values less than 5 to the value 99. We can re-code all missing values by another number (such as zero) as follows: To illustrate, let’s set up a vector that has missing values.Ī <- c(3, 2, NA, 5, 3, 7, NA, NA, 5, 2, 6) In R, you can re-code an entire vector or array at once. It’s almost never the case that the data are set up exactly the way you need them for your analysis. You can use recode () directly with factors it will preserve the existing order of levels while changing the values. For more complicated criteria, use casewhen (). One data manipulation task that you need to do in pretty much any data analysis is recode data. This is an S3 generic: dplyr provides methods for numeric, character, and factors.
