0

Here is my data Frame "crime":

District  Premise Weapon
313       99      99
316       NA
314       20      99
312       13      40
312       9       99

I have a separate list of what all the codes mean. For example, 99 in premise means "residence", 20 means "Street". 99 in Weapon means "hands", 40 means "blunt object".

In another post on stackflow, I was able to use the following code for my purpose:

crime$Premise[crime$Premise == 13] <- "House"

This worked but I realized I have 30 different codes in Premise and Weapon. There has to be a more efficient way of writing the code instead of copy and pasting the code above in multiple times and replacing the integer with the string.

*note, 99 means something else under Premise and something else in Weapon.

What is the best way to write this, so I can replace all the numbers with corresponding codes? Thank you in advance!

sabih4911
  • 1
  • 1
  • 4
    Use `?factor`s, or a lookup vector. – Rich Scriven Dec 30 '16 at 20:24
  • 2
    It might help if you gave a more complete example (like the code translations for all the codes shown in your current example, along with expected output), maybe also explaining why you have both blanks and NAs... – Frank Dec 30 '16 at 20:26
  • Another alternative would be to use a hash table from the package hash, – G5W Dec 30 '16 at 20:34

1 Answers1

0

if you don't want to build an index vector, you can use recode :

  x<-data.frame(district=c(313,316,314),premise=c(99,NA,20),Weapon=c(99,"",99))

      district premise Weapon
    1      313      99     99
    2      316      NA       
    3      314      20     99

x$premise<-recode(x$premise,"99"="residance","20"="Street")

  district   premise Weapon
1      313 residance     99
2      316      <NA>       
3      314    Street     99
Nooga
  • 55
  • 7