简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM