R/readSAS.R

Defines functions readSAS

Documented in readSAS

# last modified 2020-05-11 by J. Fox

readSAS <- function(file, rownames=FALSE, stringsAsFactors=FALSE){
    Data <- as.data.frame(haven::read_sas(file))
    if (rownames){
        check <- length(unique(col1 <- Data[[1]])) == nrow(Data)
        if (!check) warning ("row names are not unique, ignored")
        else {
            rownames(Data) <- col1
            Data[[1]] <- NULL
        }
    }
    if (stringsAsFactors){
        char.cols <- sapply(Data, class) == "character"
        if (any(char.cols)){
            for (col in names(Data)[char.cols]){
                fac <- Data[, col]
                fac[fac == ""] <- NA
                Data[, col] <- as.factor(fac)
            } 
        }
    }
    Data
}

Try the RcmdrMisc package in your browser

Any scripts or data that you put into this service are public.

RcmdrMisc documentation built on Sept. 27, 2023, 1:06 a.m.