# A question and an answer about recoding several factors simultaneously in R

**eKonometrics**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**plyr**and

**dplyr**. Recoding factors, which could prove to be a daunting task especially for variables that have many categories, can easily be accomplished with these packages. However, it is important for those learning Data Science to understand how the basic R works.

**as.numeric**option, I could see the internal level structure for the respective character notation. Let’s say, I would like to recode categories

**a**and

**f**as missing. I can accomplish this with the following code.

**a**and

**f.**

**a**and

**f**to

*grades*. The following code, I thought, would work, but it didn’t. It returns varying and erroneous answers.

Hence the question: Why one method works and the other doesn’t? Looking forward to responses from R experts.

## The Answer

lebatsnok (https://stackoverflow.com/users/2787952/lebatsnok) answered the question on stackoverflow. The solution is simple. The following code works:

“levels(x) is a character vector with length 6, as.numeric(x) is a logical vector with length 300. So you’re trying to index a short vector with a much longer logical vector. In such an indexing, the index vector acts like a “switch”, TRUE indicating that you want to see an item in this position in the output, and FALSE indicating that you don’t. So which elements of levels(x) are you asking for? (This will be random, you can make it reproducible with set.seed if that matters.”

**leave a comment**for the author, please follow the link and comment on their blog:

**eKonometrics**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.