3

This is a very basic question, but I am using the replace() function to recode values that switch half-way through the years of reporting in my dataset. The key switches, so I am converting old character values to new ones.

Example: For the variable "animaltype": Old code, cat is reported as "CAT". New code, cat is reported as "CAT_unit"

I use the basic code:

animaltype = replace(animaltype, animaltype == "CAT", "CAT_unit")

within my dplyr piping to make sure all old responses of "CAT" and the new ones coded as "CAT_unit" are now both counted as "CAT_unit".

Individually, this works. However, I want to do this for other units. For example, I want to simultaneously convert all "DOG"s to "DOG_unit". Is there a way to do this within the same function/line of code. Or, do I need to create another replace function entirely?

I have seen using casewhen and ifelse as alternatives, but for convenience it would be ideal to use the replace function within my dplyr piping. I particularly want to avoid casewhen to avoid the conversion of other unspecified values to NAs, because I only have to recode certain units and retain the majority as is. Is this possible? Or would I have to recode them all individually? What is the most succinct way to do this?

flâneur
  • 633
  • 2
  • 8
  • `animaltype %>% replace(., list=c('DOG', 'CAT', 'MOUSE'), values=c('DOG_unit', 'CAT_unit', 'MOUSE_unit'))[.]` should do it. – jay.sf Jul 13 '22 at 16:15

0 Answers0