Emily Jones
Emily Jones

Reputation: 45

How do you recode a variable?

I have a variable (animal) that sits in a data frame (data). It is coded 1 = dog, 2 = cat, 3 = bunny, 4 = horse, 5 = monkey.

I want to recode it so that horse and bunny = 2 and everything else = 1. How do I do this?

Upvotes: 1

Views: 51

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76673

Here is a way. Untested, since there are no data.

  • The logical condition data$animal %in% 3:4 returns FALSE/TRUE, coded as 0/1;
  • add 1L to get 1/2

That's it.

data$animal <- 1L + (data$animal %in% 3:4)

Upvotes: 2

Related Questions