Skip to content

Instantly share code, notes, and snippets.

@elinw

elinw/recoding.r Secret

Last active May 17, 2021 03:53
Show Gist options
  • Save elinw/fc73a5555ea6706a92b437715036093e to your computer and use it in GitHub Desktop.
Save elinw/fc73a5555ea6706a92b437715036093e to your computer and use it in GitHub Desktop.
# I pulled out the two columns from the list in the package
value_broad <- sapply(broad, "[[", 1)
input_broad <- names(broad)
# using named vector
values_named <- value_broad
names(values_named) <- input_broad
# nv is the named vectors
gender_named_vector <- function(x, nv, fill){
recoded<- nv[trimws(tolower(x))]
if (fill == TRUE){
recoded <- ifelse(is.na(recoded), x, recoded)
}
unname( recoded )
}
# using hash
# Create an environment
# create the hash table in the environment
# @example letters_a <- create_dictonary(dict_name = "letters_a", key =letters, value = LETTERS)
# This should be assigned to the same name as dict_name to avoid problems.
create_dictonary <- function(dict_name , key, value){
dictionary <- list()
dictionary[["dict"]] <-assign(dict_name, new.env( parent = emptyenv()))
as.environment( Map(assign, key, value,
MoreArgs=list(envir = dictionary[["dict"]]))
)
}
# Function to retrieve a value for a key
get_value <- function(x, dict){
dict[[x]]
}
# Add new pair to adictonary
# dict here is the environmnt you have already created.
add_key_value <- function(key, value, dict){
dict[[key]] <-value
}
# Just calling it this to distingsuish from recode_gender().
# Of course you could think of this as more generic than gender.
recode_hash <- function(x, hashname, fill){
matched_index <- which(trimws(tolower(x)) %in% names(hashname))
recoded <- character(length = length(x))
recoded[matched_index]<-vapply(
tolower(trimws(x[matched_index])),
get_value, hashname, FUN.VALUE = c("character"))
if (fill == TRUE){
recoded[-matched_index] <- x[- matched_index]
}
recoded
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment