Search code examples
rmapping

Map names to codes and use mapping to replace names in other objects


Here is a representation of my data

A list of hospitals

ls_Hospital<-c("Hospital1", "Hospital2", "Hospital3", "Hospital4", "Hospital5") # a vector

I have another list of certain of hospitals with different parameters associated with them.

list_of_hospit_param<-list(Hospital1=c("A","B","C"), Hospital2=c("C","Z","E"),Hospital4=c("K"))

I Want to anonymize hospital names, by replacing them with codes

I firstly mapped hospital names to the codes:

codes<-c("A","B","C","L","Z","X")

hospital_mapping<-setNames(codes, ls_Hospital)

I now want to completely change the names of the hospitals and replace them with their corresponding code, in each of the data sets ls_Hospital and list_of_hospit_param.

For example the list_of_hospit_param will be replaced by this:

list(A=("A","B","C"), B=c("C","Z","E"),L=c("K"))

Solution

  • (ls_Hospital <- c(
      "Hospital1", "Hospital2",
      "Hospital3", "Hospital4",
      "Hospital5"
    ))
    (list_of_hospit_param <- list(
      Hospital1 = c("A", "B", "C"),
      Hospital2 = c("C", "Z", "E"),
      Hospital4 = c("K")
    ))
    
    (codes <- c("A", "B", "C", "L", "Z", "X"))
    
    hospital_mapping <- setNames(codes, ls_Hospital)
    
    # make an ls_Hospital_2 from renaming ls_Hospital by the hospital mapping
    (ls_Hospital_2 <- unname(hospital_mapping[ls_Hospital]))
    
    # make an list_of_hospit_param_2 from renaming list_of_hospit_param by the hospital mapping
    list_of_hospit_param_2 <- list_of_hospit_param
    (nms_1 <- names(list_of_hospit_param_2))
    names(list_of_hospit_param_2) <- unname(hospital_mapping[nms_1])
    
    list_of_hospit_param_2