R/to_NA.R

Defines functions to_NA

Documented in to_NA

#' Transfer data to NA
#'
#' @param x dataframe or list
#' @param dont_know logical. whether convert don't know to NA
#' @param refused logical. whether convert refused to NA
#'
#' @return dataframe or list
#' @export
#'
to_NA <- function(x,dont_know=TRUE,refused=TRUE){
    if (is.data.frame(x)){
        for (i in 1:ncol(x)) {
            x[,i][grepl("don\\'{0,}t {0,}know",x[,i],TRUE)] <- NA
            x[,i][grepl("refused",x[,i],TRUE)] <- NA
        }
    }else if (is.list(x)){
        for (j in 1:length(x)) {
            xj <- x[[j]]
            for (i in 1:ncol(xj)) {
                xj[,i][grepl("don\\'{0,}t {0,}know",xj[,i],TRUE)] <- NA
                xj[,i][grepl("refused",xj[,i],TRUE)] <- NA
            }
            x[[j]] <- xj
        }
    }else if(is.character(x)){
        x[grepl("don\\'{0,}t {0,}know",x,TRUE)] <- NA
        x[grepl("refused",x,TRUE)] <- NA
    }
    return(x)
}
yikeshu0611/nhanesR documentation built on Jan. 29, 2022, 6:08 a.m.