The following exercise is intended to test the glmnet function for Generalized Linear Model to create a regression model that predicts the symptoms severity level on patients from a database of bio-markers information.
As an overall approach, the code will read the data from an excel worksheet, then it will perform an Exploratory Data Analysis, then the data will be manipulated and transform so that glmnet function can be used to get the prediction model. Along the code, the assumptions for manipulation and transformation of the data will be explained, no in depth knowledge of medicine is used, just the common understanding of the nature of the data and values.
The bio-markers data is a collection of laboratory test results and general information of the patients, along with it, for each observation the level of severity on the symptoms which is classified as “mild”, “moderate” and “severe”.
Once the working directory is defined to established the location of the excel file, let’s read the data using the xlsx library, will be saved in a data frame class type, named data_raw.
install.packages("readxl",repos = "http://cran.us.r-project.org")
library(readxl)
library(Matrix)
library(dplyr)
data_raw <- read_excel("biomarkers-DCH chimpu3.xlsx",sheet="Sheet1",col_names=TRUE)
str(data_raw)
By applying the str() function we notice the data has been read most of them as characters, some logic and a few numeric variables, the data contains 3062 observations of 61 variables. The dependent variable (output) is called Category and it is a factor type variable, which indicate the severity level of symptoms in a patient from a certain disease. These levels are: mild, moderate and severe.
Now we are going to make a quick review on the values of the Category variable, so to know if we have a clear value in each observation.
unique(data_raw$`Category (Asymptomatic/mild /moderate/severe)`)
## [1] "mild" "severe" "moderate" "mid" "mol" "moil"
There are more than 3 different values for this variable, it is not the intention of this exercise to speculate on the non defined values for the dependent variable, instead those rows with a non define output will be remove, before doing that, we need to know how many will that be:
sum(!(data_raw$`Category (Asymptomatic/mild /moderate/severe)` %in% c("mild","severe","moderate")))
## [1] 3
drop_list <- which(!(data_raw$`Category (Asymptomatic/mild /moderate/severe)`
%in% c("mild","severe","moderate")))
data_raw <- data_raw[-drop_list,]
dim(data_raw)
## [1] 3059 61
There were 3 observations with symptoms’ severity level undefined, after removing those the database is now 3059 x 61.
By looking at the variable description in the name of each column, most of them must be numeric since they are bio-markers usually from laboratory test, expressed as percentages, ratios, time or other numeric units. Since almost all of them are character type in the data frame, means, they have to be transformed onto numeric type, during this process some data might be lost due to typo errors.
Let’s look at all variables in the data frame to see how many NAs are in the columns:
variables_table <- colSums(!is.na(data_raw))
barplot(variables_table, xlab = "Variable", ylab ="Number of non-NA")
Note that there are some columns with very few or no data which will likely no have impact on the output. Let’s set a limit of minimum 10% of database size so to keep the variable for the analysis, the rest will be remove. The following code will find the variables with less than 300 observations and remove them from the data frame:
var_tobeout <- which(variables_table < 300)
data_raw <- data_raw[,-var_tobeout]
print(var_tobeout)
## RBS hct/Packed cell Volume(PCV)(%)
## 9 10
## RWD-CV BLAST %
## 15 25
## PROMYELOCYTE % MYELOCYTE %
## 26 27
## METAMYELOCYTE % nRBC %
## 28 29
## GLUCOSE(FASTING)mg/dl GLUCOSE(POST PRANDIAL)mg/dl
## 31 32
## CALCIUM(mEq/L) PROTHROMBIN TIME(PT)(sec)
## 48 49
## APTT(sec) INR
## 50 51
## TROPONIN-I (ng/ml) NT-PROBNP (pg/ml)
## 56 57
## CK-MB( ng/ml) ALK
## 58 59
## INDERECT S.(PP)
## 60 61
dim(data_raw)
## [1] 3059 41
The database is now 3059 x 41, columns 1 to 4 have general information that are not related with the symptoms’ level of severity, below is the list the columns will be removed and the output variable will be move to the first column.
head(names(data_raw),4)
## [1] "Sl No" "Name" "Date" "Lab no."
data_raw <- data_raw[,-c(1,2,3,4)]
data_raw <- data_raw[,c(3,1,2,4:ncol(data_raw))]
Review the database again to look at the type of variables we have now:
str(data_raw)
## tibble [3,059 × 37] (S3: tbl_df/tbl/data.frame)
## $ Category (Asymptomatic/mild /moderate/severe): chr [1:3059] "mild" "severe" "mild" "mild" ...
## $ Age (yrs/months) : chr [1:3059] "A" "A" "60 Yrs" "24 yrs" ...
## $ Gender : chr [1:3059] "M" "M" "F" "F" ...
## $ hemoglobin(g/dl) : chr [1:3059] NA NA "15" "10.9" ...
## $ RBC COUNT(106/ml) : chr [1:3059] NA NA "4.84" "4.26" ...
## $ MCV(fl) : chr [1:3059] NA NA "87.2" "78.6" ...
## $ MCH(pg) : chr [1:3059] NA NA "3.1.1" "25.5" ...
## $ MCHC(gm/dl) : chr [1:3059] NA NA "35.6" "32.5" ...
## $ RDW-SD : chr [1:3059] NA NA "44.2" "43.7" ...
## $ WBC/TOTAL LEUCOCYTE COUNT(TLC)(103/cumm) : chr [1:3059] NA NA "61400" "4.150" ...
## $ NEURTOPHIL % : chr [1:3059] NA NA "58.2" "54.7" ...
## $ LYMPHOCYTE % : chr [1:3059] NA NA "34.700000000000003" "33.7" ...
## $ MONOCYTE % : chr [1:3059] NA NA "5-0" "6.9" ...
## $ EOSINOPHIL % : chr [1:3059] NA NA "2.1" "4.5" ...
## $ BASOPHIL % : chr [1:3059] NA NA NA NA ...
## $ ESR (mm AEFH) : chr [1:3059] NA NA "45" "47" ...
## $ BLOOD GROUP : chr [1:3059] NA NA NA NA ...
## $ PLATELET( 105/cumm) : chr [1:3059] NA NA "233" "151" ...
## $ GLUCOSE(RANDOM) mg/dl : chr [1:3059] NA NA NA NA ...
## $ UREA mg/dl : chr [1:3059] NA NA "20.399999999999999" "13.3" ...
## $ CREATININE mg/dl : chr [1:3059] NA NA "0.9" "0.80" ...
## $ TB/BILIRUBIN(TOTAL)mg/dl : chr [1:3059] NA NA "0.9" NA ...
## $ DB/BILIRUBIN(DIRECT)mg/dl : chr [1:3059] NA NA "0.307" NA ...
## $ BILIRUBIN(INDIRECT)mg/dl : chr [1:3059] NA NA NA NA ...
## $ AST(SGOT)IU/L : chr [1:3059] NA NA "84.1" NA ...
## $ ALT(SGPT)IU/L : chr [1:3059] NA NA "31.7" NA ...
## $ TP/TOTAL PROTEIN( g/dl) : chr [1:3059] NA NA "8.0" NA ...
## $ ALBUMIN( g/dl) : chr [1:3059] NA NA "3.16" NA ...
## $ GLOBULIN( g/dl) : chr [1:3059] NA NA NA NA ...
## $ SODIUM(mEq/L) : chr [1:3059] NA NA "138.4" "140.5" ...
## $ POTASSIUM(mEq/L) : chr [1:3059] NA NA "3.57" "3.92" ...
## $ CHLORIDE(mEq/L) : chr [1:3059] NA NA "97.8" "101.4" ...
## $ Serology : chr [1:3059] NA NA NA NA ...
## $ IL-6 (pg/ml) : chr [1:3059] NA NA NA NA ...
## $ CRP( ng/ml) : chr [1:3059] NA NA NA NA ...
## $ D-DIMER (<FEU/ml) : chr [1:3059] NA NA NA NA ...
## $ FERRITIN (ng/ml) : chr [1:3059] NA NA NA NA ...
There are 37 variables, 1 dependent (Category) and 36 predictors, in 3059 observations. Within the predictor we have mostly numeric variables, as we can tell by the column name and description, let’s look a 2 of them:
But we do have some variables that would likely be factorial, those are: Gender, BLOOD GROUP and Serology. We will require more work on those in order to get them as factor variables. Let’s look at the number of values in the database which contain text or letters:
cat_vars <- vector()
sum_cat_vars <- vector()
for (i in (1:ncol(data_raw))) {
a <- sum(grepl("[A-Z,a-z]+",data_raw[[i]]))
sum_cat_vars <- c(sum_cat_vars,a)
if (a>0){cat_vars <- c(cat_vars,i) }
}
print(sum_cat_vars)
## [1] 3059 726 2497 0 1 0 0 0 0 17 0 0 0 0 0
## [16] 0 484 0 0 0 0 0 2 0 0 0 0 0 1 0
## [31] 0 1 662 0 0 1 0
By looking at this table, variables 2, 3, 17 and 33 have text in a fairly large number of values, as we mentioned before variables 3, 17 and 33 were expected to be factorial, except for variable 2 (Age) which in this case the text are the description of year, months or even days.
The main objective on data transformation and pre-processing is to get a tidy data set suitable for a General Linear Regression, also, every variable has to be defined with a class according to the type of analysis (binomial, multinomial, etc).
In this particular case we know the output is a factor variable that can have the following levels: mild, moderate and severe. First step will be to transform this variable into factor class, as follows:
data_raw[[1]] <- as.factor(data_raw[[1]])
Now let’s transform those variables described as numeric by applying the as.numeric function, during this process some data will be lost if they have typo errors, bad punctuation or texts. Let’s built a list of all columns of numeric variables, then record the number of NAs per column before the transformation, after converting them into numeric, get again the number of NAs.
list_num_col <- 1:ncol(data_raw)
non_num <- c(1,2,3,17,33)
list_num_col <- list_num_col[!(c(list_num_col) %in% non_num)]
print(colSums(is.na(data_raw[,list_num_col])))
## hemoglobin(g/dl)
## 893
## RBC COUNT(106/ml)
## 931
## MCV(fl)
## 926
## MCH(pg)
## 929
## MCHC(gm/dl)
## 927
## RDW-SD
## 929
## WBC/TOTAL LEUCOCYTE COUNT(TLC)(103/cumm)
## 925
## NEURTOPHIL %
## 923
## LYMPHOCYTE %
## 924
## MONOCYTE %
## 924
## EOSINOPHIL %
## 926
## BASOPHIL %
## 957
## ESR (mm AEFH)
## 1020
## PLATELET( 105/cumm)
## 938
## GLUCOSE(RANDOM) mg/dl
## 1702
## UREA mg/dl
## 956
## CREATININE mg/dl
## 965
## TB/BILIRUBIN(TOTAL)mg/dl
## 1002
## DB/BILIRUBIN(DIRECT)mg/dl
## 1003
## BILIRUBIN(INDIRECT)mg/dl
## 1011
## AST(SGOT)IU/L
## 1005
## ALT(SGPT)IU/L
## 1008
## TP/TOTAL PROTEIN( g/dl)
## 1006
## ALBUMIN( g/dl)
## 1006
## GLOBULIN( g/dl)
## 1011
## SODIUM(mEq/L)
## 1132
## POTASSIUM(mEq/L)
## 1132
## CHLORIDE(mEq/L)
## 1132
## IL-6 (pg/ml)
## 2254
## CRP( ng/ml)
## 2140
## D-DIMER (<FEU/ml)
## 1984
## FERRITIN (ng/ml)
## 2212
sum(colSums(is.na(data_raw[,list_num_col])))
## [1] 36733
Right now, there are 36,733 NAs in the numeric columns, let’s apply the convert function (as.numeric), then look at the new number.
for (i in list_num_col) {
data_raw[,i] <- as.numeric(unlist(data_raw[,i]))
}
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
print(colSums(is.na(data_raw[,list_num_col])))
## hemoglobin(g/dl)
## 893
## RBC COUNT(106/ml)
## 932
## MCV(fl)
## 926
## MCH(pg)
## 931
## MCHC(gm/dl)
## 927
## RDW-SD
## 929
## WBC/TOTAL LEUCOCYTE COUNT(TLC)(103/cumm)
## 942
## NEURTOPHIL %
## 925
## LYMPHOCYTE %
## 924
## MONOCYTE %
## 925
## EOSINOPHIL %
## 926
## BASOPHIL %
## 959
## ESR (mm AEFH)
## 1020
## PLATELET( 105/cumm)
## 938
## GLUCOSE(RANDOM) mg/dl
## 1703
## UREA mg/dl
## 957
## CREATININE mg/dl
## 965
## TB/BILIRUBIN(TOTAL)mg/dl
## 1002
## DB/BILIRUBIN(DIRECT)mg/dl
## 1005
## BILIRUBIN(INDIRECT)mg/dl
## 1012
## AST(SGOT)IU/L
## 1005
## ALT(SGPT)IU/L
## 1008
## TP/TOTAL PROTEIN( g/dl)
## 1006
## ALBUMIN( g/dl)
## 1006
## GLOBULIN( g/dl)
## 1012
## SODIUM(mEq/L)
## 1132
## POTASSIUM(mEq/L)
## 1132
## CHLORIDE(mEq/L)
## 1134
## IL-6 (pg/ml)
## 2254
## CRP( ng/ml)
## 2140
## D-DIMER (<FEU/ml)
## 1984
## FERRITIN (ng/ml)
## 2212
sum(colSums(is.na(data_raw[,list_num_col])))
## [1] 36766
Only 33 values were lost after the transformation of the numeric columns, there is no point on correct the ones lost.
Next step is to work out the Age variable, since the texts found on the column are descriptions of whether they are years, months, days or even the letter A that might indicates the patient is an adult.
working_vector <- data_raw$`Age (yrs/months)`
working_vector <- toupper(working_vector)
texts_in_age <- grep("[A-Z]",working_vector)
unique(working_vector[texts_in_age])
## [1] "A" "60 YRS" "24 YRS" "68YRS" "34 YRS"
## [6] "9 DAYS" "10 DAYS" "44 YRS" "28 YRS" "25YRS"
## [11] "68 YRS" "42 YRS" "23 YRS" "27 YRS" "41 YRS"
## [16] "52 YRS" "35 YRS" "65 YRS" "32 YRS" "18 YRS"
## [21] "75 YRS" "39 YRS" "58 YRS" "25 YRS" "40 YRS"
## [26] "3 MONTH" "INFANT" "1MTH 15DAYS" "12 DAYS"
The text YRS may just be removed to left the numbers meaning the years of the patient, in case of values with texts of DAYS, MTH/MONTH and INFANT, the whole value may be substitute by the number 1, meaning 1 year of age for the patient. A values will be substitute by the average age of an adult. We will copy the Age column to a working vector in order to transform the values, then return it to the database.
values_A <- grep("^A",working_vector) # Create a list with text only with "A"
working_vector <- gsub("YRS","",working_vector) #
list_infants <- grep("MONTH|MTH|INFANT|DAYS",working_vector) # Create list of values with MONTH, MTH, INFANT and DAYS texts infant values
working_vector[list_infants] <- 1 # Assign 1 at infant values
adult_vector <- as.numeric(working_vector[-c(list_infants,values_A)]) # Vector of numeric values and NAs in Age
working_vector[values_A] <- mean(adult_vector,na.rm=TRUE) # Assign the mean age of adults from original data to values with "A"
data_raw$`Age (yrs/months)` <- as.numeric(working_vector)
Now, let’s transform the categorical variables (BLOOD GROUP and Serology), for the BLOOD GROUP variable we know there should be 8 levels (A+, A-, B+, B-, AB+, AB-,O+ and O-), take a look at the unique values within the column:
unique(data_raw$`BLOOD GROUP`)
## [1] NA "\"O\" Positive" "\"A\" Positive" "\"B\" Positive"
## [5] "\"AB\" Negative" "\"AB \"POSITIVE" "AB Positive" "\"O\" POSITIVE"
## [9] "\"B\" NEGATIVE" "\"AB\" NEGATIVE" "\"A\" NEGATIVE" "\"A\" POSITIVE"
## [13] "\"B\" POSITIVE" "\"AB\" POSITIVE" "\"O' POSITIVE" "\"A' POSITIVE"
## [17] "A' POSITIVE" "\"O\"POSITIVE" "\"B\" POSIOTIVE" "\"B' POSITIVE"
## [21] "\"O\" NEGATIVE" "A\" POSITIVE" "\"AB' POSITIVE"
There are more than 8 different levels as it now, first step is to get all letters to caps eliminate the punctuation, then define the patterns that in a unique way will identify each blood group in the texts exiting. Once is indentofied we can substitute the value for a proper text.
data_raw$`BLOOD GROUP` <- toupper(data_raw$`BLOOD GROUP`)
data_raw$`BLOOD GROUP` <- gsub("[[:punct:]]", "",data_raw$`BLOOD GROUP`)
unique(data_raw$`BLOOD GROUP`)
## [1] NA "O POSITIVE" "A POSITIVE" "B POSITIVE" "AB NEGATIVE"
## [6] "AB POSITIVE" "B NEGATIVE" "A NEGATIVE" "OPOSITIVE" "B POSIOTIVE"
## [11] "O NEGATIVE"
By listing the unique values of BLOOD GROUP we note there are 2 extra texts different from the 8 expected, these are typo errors OPOSITIVE and B POSIOTIVE), we will change those values to O POSITIVE and B POSITIVE respectively, then convert the column to factor:
data_raw$`BLOOD GROUP`[which(data_raw$`BLOOD GROUP` == "OPOSITIVE")] <- "O POSITIVE"
data_raw$`BLOOD GROUP`[which(data_raw$`BLOOD GROUP` == "B POSIOTIVE")] <- "B POSITIVE"
data_raw$`BLOOD GROUP` <- as.factor(data_raw$`BLOOD GROUP`)
A similar approach is going to be taken with Serology variable, this is a collection of test results for diseases that compromise the patient health, so for the sake of the analysis any positive or reactive result will be considered as positive.
data_raw$Serology <- toupper(data_raw$Serology)
working_vector <- data_raw$Serology
texts_in_Serology <- grep("[A-Z]",working_vector)
unique(working_vector[texts_in_Serology])
## [1] "HBSAG(NEG)"
## [2] "HBSAG (NEG)"
## [3] "HIV- NG. HBSAG-POS. VDRC-N.R"
## [4] "HIV- NG. HBSAG-NG. VDRC-N.R"
## [5] "HBSAG (NEG).VDAC-NR"
## [6] "HBSAY-NR. HIV-NR. HCV-NR"
## [7] "HCV-NR. HIV-NR."
## [8] "HCV-NEG. VDRC-NR"
## [9] "HCV-NEG."
## [10] "HBSAG-NEG. VDRC-NG HIV-NEG."
## [11] "HBSAG-NEG. VDRC-NG HIV-NEG. HCV .NG"
## [12] "ABSAG-HCV-HIV=NEG."
## [13] "ABSAG-HIV=NEG."
## [14] "ABSAG-HCV=NEG."
## [15] "HIV-NEGATIVE"
## [16] "HCV-HIV-NEGATIVE"
## [17] "HBSAG-NEG. HIV-NEG."
## [18] "HBSAG-NEG. VDRC-NG HIV-NEG. HCV-NON-REACTIVE"
## [19] "HBSAG-NEG.HCV-N.R.HIV-NEG"
## [20] "HBSAG-NEG.HCV-N.R.HIV-NEG. VDRL- NON-REACTIVE"
## [21] "HBSAG-NEG.HCV-N.R.HIV-NEG. VDRL-REACTIVE"
## [22] "HBSAG-NEGATIVE"
## [23] "HBSAG-NEG.VDRL-N.R.HIV-NEG"
## [24] "HBSAG-NEG.HCV-NEG.HIV-NEG"
## [25] "HBSAG-POS.HCV-NEG.HIV-NEG"
## [26] "WIDAL-O-REACTIVE.H-REACTIVE"
## [27] "HBSAG-NEG.VDRL-NR"
## [28] "HBSAG-NEG.HCV-NEG.HIV-NEG.VDRL-NON REACTIVE"
## [29] "HBSAG-NEG.HIV-NEG"
## [30] "HBSAG-NEG.HCV-NEG.VDRL-NR"
## [31] "HBSAG-NEG.VDRL-NR.HIV-NEG"
## [32] "HBSAG-NEG.VDRL-POS.HIV-NEG"
## [33] "HCV-NEGATIVE"
## [34] "HBSAG-NEG.HCV-NEG."
## [35] "HBSAG-NEG.HIV-NEG.HCV-NEG"
## [36] "HBSAG-NEG.VDRL-NEG.HIV-NEG"
## [37] "HBSAG-POSITIVE,HCV-NEG"
## [38] "HBSAG-NEG,HCV-NEG,HIV-NEG"
## [39] "VDRL-NEG,HCV-NEG,HIV-NEG"
## [40] "HBSAG-POS,HCV-NEG,HIV-NEG, VDRL-NON-REACTIVE"
## [41] "HBSAG-NEG,VDRL-N.R,HIV-NEG"
## [42] "HBSAG-NEG,HCV-NEG"
## [43] "HBSAG-NEG,VDRL-N.R,HCV-NEG"
## [44] "HBSAG-NEG,HIV-NEG,HCV-NEG"
## [45] "HBSAG-NEG,HIV-NEG"
## [46] "HBSAG - NEGATIVE"
## [47] "HBSAG-REACTIVE,HCV-NEG"
## [48] "HBSAG-NEG,VDRL-NON-REACTIVE"
## [49] "HBSAG-POS,HIV-NEG,HCV-NEG"
## [50] "HBSAG-NEG,HIV-NEG,HCV-NEG, VDRL - NEGATIVE"
## [51] "HBSAG - NEGATIVE,HIV -,NEGATIVE"
## [52] "HBSAG - NEGATIVE,VDRL -NR"
## [53] "HBSAG-NEG,HIV-NEG,VDRL-NR"
## [54] "HBSAG-NEGATIVE,VDRL-NR"
## [55] "HBSAG-NEG,HCV-NEG,HIV-NEG, VDRL - REACTIVE"
## [56] "HBSAG-NEG,HIV-NEG,HCV-NEG, VDRL - NON REACTIVE"
## [57] "HBSAG-NEG, HIV-NEG"
## [58] "HCV - NEGATIVE"
## [59] "HBSAG-NEG, HCV-NEG"
## [60] "HBSAG-NEG,HIV-NEG,VDRL-POS"
## [61] "HBSAG-NEG,HIV-NEG,HCV-NEG, VDRL-NON-REACTIVE"
## [62] "HBSAG- NEG,HIV-NEG"
## [63] "HBSAG-NEG,HIV-NEG,HCV - POSITIVE, VDRL - NON-REACTIVE"
## [64] "HBSAG-NEG,HIV-NEG,VDRL-RE"
## [65] "HIV - NEGATIVE"
## [66] "HBSAG-REACTIVE,HIV-NEG"
## [67] "HBSAG-NEG,HIV-NEG,HCV-NEG, VDRL - NON-REACTIVE"
## [68] "HBSAG-NEG,HIV-POS,HCV-NEG"
## [69] "HBSAG-NEG,HIV-NEG,HCV-POS"
## [70] "HIV-NEG,HCV-NEG"
## [71] "HIV - POSITIVE"
## [72] "HBSAG-POSITIVE,HIV-NEG"
## [73] "HCV-NEG,HIV-NEG"
## [74] "HBSAG-NEG,HIV-NEG,HCV-NEG, VDRL - REACTIVE"
## [75] "HBSAG-POS,HIV-NEG,VDRL-NR"
## [76] "HBSAG-NEG, VDRL-NON-REACTIVE"
## [77] "VDRL - REACTIVE"
## [78] "HBSAG-POS,HIV-NEG,HCV-NEG, VDRL - NON-REACTIVE"
## [79] "HBSAG-POS,HIV-NEG,HCV-POS, VDRL - NON-REACTIVE"
working_vector <- gsub("[[:punct:]]", "",working_vector)
working_vector <- gsub(" ","",working_vector)
list_Ser_Pos <- grep("POS|VDRLR|HBSAGR|HCVR",working_vector) # Identifies all text with POS or POSITIVE result and REACTIVE result
working_vector[list_Ser_Pos] <- "POSITIVE"
list_Ser_Neg <- texts_in_Serology[!(texts_in_Serology %in% list_Ser_Pos)]
working_vector[list_Ser_Neg] <- "NEGATIVE"
data_raw$Serology <- as.factor(working_vector)
Last category variable is Gender, there are only 2 levels F or M, let’s look at the column and perform the changes:
unique(data_raw$Gender)
## [1] "M" "F" NA "m" "f" "mil" "13.7" "A"
Values not identified will be set as NAs.
data_raw$Gender <- toupper(data_raw$Gender)
list_non_identified <- which(data_raw$Gender == "MIL")
data_raw$Gender[list_non_identified] <- NA
list_Gender_values <- grep("M|F",data_raw$Gender)
data_raw$Gender[-list_Gender_values] <- NA
data_raw$Gender <- as.factor(data_raw$Gender)
The database is now in the right variable class, but it is still not a tidy dataset since there are NAs, now we are going to process the data to get a tidy. To process the numeric variables in this case there is a need to eliminate the outliers in the data to keep out noise from the analysis, then, the missing data will be replaced by the mean of the existing data without outliers.
First step, define a function to get the outliers in every column, considering a 95 percentile range:
remout <- function(vector_in) {
# vector_in <- as.vector(vector_in)
Q <- quantile(vector_in, probs=c(0.25,0.75), na.rm=TRUE)
iqr <- IQR(vector_in, na.rm=TRUE)
up <- Q[2]+1.5*iqr # upper range
down <- Q[1]-1.5*iqr # lower range
which(vector_in < down | vector_in > up)
}
The following routine will get the mean by every numeric column, after taking out all outliers, and then fill the NAs with that value.
names_numeric <- names(select_if(data_raw, is.numeric))
for (i in names_numeric) {
out_numbers <- remout(unlist(data_raw[,i]))
value_mean <- mean(data_raw[[i]][-out_numbers],na.rm=TRUE)
data_raw[out_numbers,i] <- value_mean
na_numbers <- which(is.na(data_raw[,i]))
data_raw[na_numbers,i] <- value_mean
}
colSums(is.na(data_raw))
## Category (Asymptomatic/mild /moderate/severe)
## 0
## Age (yrs/months)
## 0
## Gender
## 564
## hemoglobin(g/dl)
## 0
## RBC COUNT(106/ml)
## 0
## MCV(fl)
## 0
## MCH(pg)
## 0
## MCHC(gm/dl)
## 0
## RDW-SD
## 0
## WBC/TOTAL LEUCOCYTE COUNT(TLC)(103/cumm)
## 0
## NEURTOPHIL %
## 0
## LYMPHOCYTE %
## 0
## MONOCYTE %
## 0
## EOSINOPHIL %
## 0
## BASOPHIL %
## 0
## ESR (mm AEFH)
## 0
## BLOOD GROUP
## 2575
## PLATELET( 105/cumm)
## 0
## GLUCOSE(RANDOM) mg/dl
## 0
## UREA mg/dl
## 0
## CREATININE mg/dl
## 0
## TB/BILIRUBIN(TOTAL)mg/dl
## 0
## DB/BILIRUBIN(DIRECT)mg/dl
## 0
## BILIRUBIN(INDIRECT)mg/dl
## 0
## AST(SGOT)IU/L
## 0
## ALT(SGPT)IU/L
## 0
## TP/TOTAL PROTEIN( g/dl)
## 0
## ALBUMIN( g/dl)
## 0
## GLOBULIN( g/dl)
## 0
## SODIUM(mEq/L)
## 0
## POTASSIUM(mEq/L)
## 0
## CHLORIDE(mEq/L)
## 0
## Serology
## 2397
## IL-6 (pg/ml)
## 0
## CRP( ng/ml)
## 0
## D-DIMER (<FEU/ml)
## 0
## FERRITIN (ng/ml)
## 0
Now there is only 3 columns with NAs existing and those are the factor variables, for these columns the approach is going to be different, we cannot rely on the means of each column but to look at the distribution existing on the actual data. Gender is not that challenging because it is only 2 levels and overall the population, if nothing particular, is 50% - 50%. BLOOD GROUP has 8 different levels, so we need to get the actual distribution and apply to the the NAs rows. Same reasoning with respect to Serology, assuming the existong data is a random sample of the population.
Pre-processing Gender variable:
gender_nas <- sum(is.na(data_raw$Gender))
gender_subs <- sample(c("F","M"), size = gender_nas, prob=c(0.5,0.5),
replace=TRUE)
data_raw$Gender[is.na(data_raw$Gender)] <- gender_subs
Pre-processing BLOOD GROUP variable:
table_blood_group <- summary(data_raw$`BLOOD GROUP`)[1:8]
bloodgroup_distribution <- table_blood_group/sum(table_blood_group)
n_bg <- sum(is.na(data_raw$`BLOOD GROUP`))
blood_group <- levels(data_raw$`BLOOD GROUP`)
bg_nareplace_list <- sample(blood_group,size=n_bg,replace=TRUE,
prob=bloodgroup_distribution)
bg_na_list <- which(is.na(data_raw$`BLOOD GROUP`))
data_raw$`BLOOD GROUP`[bg_na_list] <- bg_nareplace_list
Pre-processing Serology variable:
Serology_probability <- summary(data_raw$Serology)[1:2]/sum(summary(data_raw$Serology)[1:2])
list_Serology_NAs <- which(is.na(data_raw$Serology))
list_Serology_subs <- sample(levels(data_raw$Serology), size =
length(list_Serology_NAs),
prob=
summary(data_raw$Serology)[1:2]/sum(summary(data_raw$Serology)[1:2]),
replace = TRUE)
data_raw$Serology[list_Serology_NAs] <- list_Serology_subs
colSums(is.na(data_raw))
## Category (Asymptomatic/mild /moderate/severe)
## 0
## Age (yrs/months)
## 0
## Gender
## 0
## hemoglobin(g/dl)
## 0
## RBC COUNT(106/ml)
## 0
## MCV(fl)
## 0
## MCH(pg)
## 0
## MCHC(gm/dl)
## 0
## RDW-SD
## 0
## WBC/TOTAL LEUCOCYTE COUNT(TLC)(103/cumm)
## 0
## NEURTOPHIL %
## 0
## LYMPHOCYTE %
## 0
## MONOCYTE %
## 0
## EOSINOPHIL %
## 0
## BASOPHIL %
## 0
## ESR (mm AEFH)
## 0
## BLOOD GROUP
## 0
## PLATELET( 105/cumm)
## 0
## GLUCOSE(RANDOM) mg/dl
## 0
## UREA mg/dl
## 0
## CREATININE mg/dl
## 0
## TB/BILIRUBIN(TOTAL)mg/dl
## 0
## DB/BILIRUBIN(DIRECT)mg/dl
## 0
## BILIRUBIN(INDIRECT)mg/dl
## 0
## AST(SGOT)IU/L
## 0
## ALT(SGPT)IU/L
## 0
## TP/TOTAL PROTEIN( g/dl)
## 0
## ALBUMIN( g/dl)
## 0
## GLOBULIN( g/dl)
## 0
## SODIUM(mEq/L)
## 0
## POTASSIUM(mEq/L)
## 0
## CHLORIDE(mEq/L)
## 0
## Serology
## 0
## IL-6 (pg/ml)
## 0
## CRP( ng/ml)
## 0
## D-DIMER (<FEU/ml)
## 0
## FERRITIN (ng/ml)
## 0
The database is now tidy all observations have values and all predictors too, but before going into the regression, let’s take a test on the correlation of the predictors towards the dependent variable. In order to do this, we will apply the Kruskal-Wallis test since our dependent variable is a multinomial factor one.
p_values_data <-apply(data_raw[,-1], 2,
function(x) kruskal.test(x,
data_raw$`Category (Asymptomatic/mild /moderate/severe)`)$p.value)
list_significant <- which(p_values_data < 0.05)
print(p_values_data)
## Age (yrs/months)
## 1.693910e-114
## Gender
## 3.469635e-28
## hemoglobin(g/dl)
## 4.971204e-03
## RBC COUNT(106/ml)
## 2.448705e-02
## MCV(fl)
## 2.987009e-02
## MCH(pg)
## 4.766060e-03
## MCHC(gm/dl)
## 2.231200e-02
## RDW-SD
## 1.782523e-10
## WBC/TOTAL LEUCOCYTE COUNT(TLC)(103/cumm)
## 1.092257e-24
## NEURTOPHIL %
## 6.399298e-45
## LYMPHOCYTE %
## 1.081897e-45
## MONOCYTE %
## 2.399154e-15
## EOSINOPHIL %
## 6.104890e-13
## BASOPHIL %
## 3.182343e-08
## ESR (mm AEFH)
## 1.801588e-02
## BLOOD GROUP
## 3.533095e-01
## PLATELET( 105/cumm)
## 8.817838e-03
## GLUCOSE(RANDOM) mg/dl
## 7.771728e-13
## UREA mg/dl
## 2.037867e-55
## CREATININE mg/dl
## 6.150137e-22
## TB/BILIRUBIN(TOTAL)mg/dl
## 3.189482e-06
## DB/BILIRUBIN(DIRECT)mg/dl
## 4.661437e-08
## BILIRUBIN(INDIRECT)mg/dl
## 1.885826e-01
## AST(SGOT)IU/L
## 2.111261e-06
## ALT(SGPT)IU/L
## 4.132052e-10
## TP/TOTAL PROTEIN( g/dl)
## 2.545003e-04
## ALBUMIN( g/dl)
## 5.473364e-05
## GLOBULIN( g/dl)
## 2.654138e-01
## SODIUM(mEq/L)
## 1.457376e-04
## POTASSIUM(mEq/L)
## 6.381601e-03
## CHLORIDE(mEq/L)
## 3.635718e-09
## Serology
## 5.788177e-01
## IL-6 (pg/ml)
## 2.058567e-05
## CRP( ng/ml)
## 3.317727e-03
## D-DIMER (<FEU/ml)
## 1.493223e-05
## FERRITIN (ng/ml)
## 8.103766e-15
The result of the test gives a p-value to represent the significant difference between the mean of the predictor and the different levels on the output variable, a p-value less than 0.05 indicates a strong correlation. We already create a list of predictors with this range of p-value called list_significant. Let’s saved this data on a new data frame to be used for the regression:
bio_data_final <- data_raw[,names(list_significant)]
bio_data_final <- cbind(data_raw[,1],bio_data_final)
dim(bio_data_final)
## [1] 3059 33
names(bio_data_final)
## [1] "Category (Asymptomatic/mild /moderate/severe)"
## [2] "Age (yrs/months)"
## [3] "Gender"
## [4] "hemoglobin(g/dl)"
## [5] "RBC COUNT(106/ml)"
## [6] "MCV(fl)"
## [7] "MCH(pg)"
## [8] "MCHC(gm/dl)"
## [9] "RDW-SD"
## [10] "WBC/TOTAL LEUCOCYTE COUNT(TLC)(103/cumm)"
## [11] "NEURTOPHIL %"
## [12] "LYMPHOCYTE %"
## [13] "MONOCYTE %"
## [14] "EOSINOPHIL %"
## [15] "BASOPHIL %"
## [16] "ESR (mm AEFH)"
## [17] "PLATELET( 105/cumm)"
## [18] "GLUCOSE(RANDOM) mg/dl"
## [19] "UREA mg/dl"
## [20] "CREATININE mg/dl"
## [21] "TB/BILIRUBIN(TOTAL)mg/dl"
## [22] "DB/BILIRUBIN(DIRECT)mg/dl"
## [23] "AST(SGOT)IU/L"
## [24] "ALT(SGPT)IU/L"
## [25] "TP/TOTAL PROTEIN( g/dl)"
## [26] "ALBUMIN( g/dl)"
## [27] "SODIUM(mEq/L)"
## [28] "POTASSIUM(mEq/L)"
## [29] "CHLORIDE(mEq/L)"
## [30] "IL-6 (pg/ml)"
## [31] "CRP( ng/ml)"
## [32] "D-DIMER (<FEU/ml)"
## [33] "FERRITIN (ng/ml)"
The data frame now has 32 predictors, all numeric except for Gender, the last transformation of the data is on this factor variable, the requirements by glmnet function is to have a column for each level of a factor variable with values 1 or 0 depending if the level is present or not. To make this transformation, we will use a function called model.matrix to create a dummy variable :
dummy_Gender <- model.matrix( ~ Gender -1,bio_data_final)
bio_data_final <- cbind(bio_data_final,dummy_Gender)
bio_data_final <- bio_data_final[,!(names(bio_data_final) == "Gender")]
The database is ready to apply the glmnet function to have a linear regressed model, we are going to divide the data in a 70-30 % between train and test data sets.
n <- nrow(bio_data_final)
ind <- sample(c(TRUE, FALSE), n, replace=TRUE, prob=c(0.7, 0.3))
train <- bio_data_final[ind,]
test <- bio_data_final[!ind,]
There is also another requirement for the function to input the data in a matrix format,
x <- as.matrix(train[,2:ncol(train)])
y <- as.matrix(train[,1])
n_x <- as.matrix(test[,2:ncol(test)])
n_y <- as.matrix(test[,1])
Fit the model using glmnet:
library(glmnet)
fit <- glmnet(x, y,
family = "multinomial", type.multinomial = "grouped")
Plot the behavior of Betas for the regression:
plot(fit, xvar = "lambda", label = TRUE, type.coef = "2norm")
cvfit <- cv.glmnet(x, y,
family = "multinomial", type.multinomial = "grouped")
Plot the cross-validation data to visualize the behavior of lambda and which to use for prediction:
plot(cvfit)
Use the model to predict the outcome for test database, with lambda min as the lowest error, then get the accuracy of the model:
predict_y <- predict(cvfit, newx = n_x, s = "lambda.min", type = "class")
sum(predict_y == n_y)/length(n_y)
## [1] 0.6356502
The model can predict the level of severity of the disease with a 63% accuracy having considered the NAs as mean or actual data distribution.