1

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?

zephryl
  • 14,633
  • 3
  • 11
  • 30

1 Answers1

2

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)
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66