R/nhs_varLabel.R

Defines functions nhs_varLabel

Documented in nhs_varLabel

#' label for variable
#' file path or variable names shoul be given together, no matter which is first.
#' They will be divided into files and variables according to whether they contain a path or not.
#' @param ... file path of nhs_files_pc() or variable names
#' @param tolower logical. Whether to transform lebel to be lower.
#' @return variable label
#' @export
#' @examples
#' # nhs_varLabel('seqn')
#' # all variable labels
#' # x <- nhs_varLabel()
nhs_varLabel <- function(...,tolower=FALSE){
    hold <- c(...)
    ck <- grepl(get_config_path(),hold,ignore.case = TRUE)
    files <- hold[ck]
    variable <- tolower(hold[!ck])
    if (length(files)==0) files <- nhs_files_pc(file_ext = 'varLabel')
    ck <- tools::file_ext(files) != 'varLabel'
    if (any(ck)){
        ext <- tools::file_ext(files[ck]) |> unique() |> sprintf(fmt = '\\.%s')
        files[ck] <- do::Replace0(files[ck],ext) |> sprintf(fmt = '%s.varLabel')
    }
    lapply(files, function(i){
        (Year <- prepare_years(i))
        (Item <- prepare_items(i))
        (file <- do::file.name(i) |> do::Replace0('\\.varLabel'))
        labeli <- read.delim(i,comment.char = '#')
        if (length(variable) >0){
            # ck <- labeli$name %in% variable
            ck <- lookl(labeli$name,variable,ignore.case = TRUE)
            labeli <- labeli[ck,]
            if (tolower) labeli$label <- tolower(labeli$label)
        }
        if (nrow(labeli)==0) return()
        colnames(labeli) <- c('variable','label')
        cbind(Year=Year,Item=Item,file=file,labeli)
    }) |> do.call(what = rbind)
}
yikeshu0611/nhanesR documentation built on Jan. 29, 2022, 6:08 a.m.