 # recode function in R: recode a variable ## What does recode do in R?

The recode function in R is built-in in the ‘admisc’ package. It can help you recode the variables in the object. In exact words, this function can help you replace the given value in the vector, the array, the matrix, or the data frame,… with the specified value. It can help you recode the number to the character and also recode the character to the number. Let’s take a look at the syntax of this function.

Syntax:

admisc:: recode(vec, rules, cut, values, …)

Parameters:

• vec: The vector whose value is numeric, character, or factor.
• rules: The rules for the function to recode the values.
• cut: The vector of the unique cut points.
• values: The vector of the output values.

After learning what the recode function in R is, and the syntax of this function, you will learn how to use it in the next title below.

## How to use the recode function in R?

The recode function in R can help you replace the given value in your object with the specified value.

But first, you have to install the ‘admisc’ package to work with it.

You can install the ‘admisc’ package by running the following command.

install.packages('admisc')

After installing the ‘admisc’ package, you can use the recode function.

### Use the recode function with the numeric vector

You can use the recode function with the numeric vector to replace the numbers with the characters.

Look at the example below.

# Create a vector.
vec <- rep(1:4,3) #  1 2 3 4 1 2 3 4 1 2 3 4

# Replace the numbers with the characters.
admisc:: recode(vec,"1=A; 2=B; 3= C; 4 = D")

Output

 "A" "B" "C" "D" "A" "B" "C" "D" "A" "B" "C" "D"

### Use the recode function with the character vector

You can recode the factors to the numbers by the recode function.

Look at the example below.

# Create a vector.
vec <- as.factor(c('a', 'b', 'c', 'a', 'LearnShareIT'))

# Replace the factors with the numbers.
admisc:: recode(vec,"a = 1; b:c = 2; else = NA")

Output

 1 2 2 1 NA

## Summary

You have learned about the usage, the syntax, and how to use the recode function in RBy this function, you can replace the given values in an object with the specified values. If you have any questions about this guide, leave your comment below, and I will answer your questions. We hope this tutorial is helpful to you. Thanks!

Maybe you are interested:

Posted in R