SOCR ≫ | DSPA ≫ | Topics ≫ |
In this chapter, we will discuss strategies to import
data and export
results. Also, we are going to learn the basic tricks we need to know about processing different types of data. Specifically, we will illustrate common R
data structures and strategies for loading (ingesting) and saving (regurgitating) data. In addition, we will (1) present some basic statistics, e.g., for measuring central tendency (mean, median, mode) or dispersion (variance, quartiles, range), (2) explore simple plots, (3) demonstrate the uniform and normal distributions, (4) contrast numerical and categorical types of variables, (5) present strategies for handling incomplete (missing) data, and (6) show the need for cohort-rebalancing when comparing imbalanced groups of subjects, cases or units.
Let’s start by extracting the Edgar Anderson’s Iris Data from the package datasets
. The iris dataset quantifies morphologic shape variations of 50 Iris flowers of three related genera - Iris setosa, Iris virginica and Iris versicolor. Four shape features were measured from each sample - length and the width of the sepals and petals (in centimeters). These data were used by Ronald Fisher in his 1936 linear discriminant analysis paper.
data()
data(iris)
class(iris)
## [1] "data.frame"
As an I/O (input/output) demonstration, after we load the iris
data and examine its class type, we can save it into a file named “myData.RData” and then reload it back into R
.
save(iris, file="myData.RData")
load("myData.RData")
Importing the data from "CaseStudy07_WorldDrinkingWater_Data.csv"
from these case-studies and saving it into the R dataset named “water”. The variables in the dataset are as follows:
Generally, the separator of a CSV file is comma. By default, we have optionsep=", "
in the command read.csv()
. Also, we can use colnames()
to rename the column variables.
<- read.csv('https://umich.instructure.com/files/399172/download?download_frd=1', header=T)
water 1:3, ] water[
## Year..string. WHO.region..string. Country..string.
## 1 1990 Africa Algeria
## 2 1990 Africa Angola
## 3 1990 Africa Benin
## Residence.Area.Type..string.
## 1 Rural
## 2 Rural
## 3 Rural
## Population.using.improved.drinking.water.sources......numeric.
## 1 88
## 2 42
## 3 49
## Population.using.improved.sanitation.facilities......numeric.
## 1 77
## 2 7
## 3 0
colnames(water)<-c("year", "region", "country", "residence_area", "improved_water", "sanitation_facilities")
1:3, ] water[
## year region country residence_area improved_water sanitation_facilities
## 1 1990 Africa Algeria Rural 88 77
## 2 1990 Africa Angola Rural 42 7
## 3 1990 Africa Benin Rural 49 0
which.max(water$year);
## [1] 913
# rowMeans(water[,5:6])
mean(water[,6], trim=0.08, na.rm=T)
## [1] 71.63629
This code loads CSV files that already include a header line listing the names of the variables. If we don’t have a header in the dataset, we can use the header = FALSE
option to fix it. R will assign default names to the column variables of the dataset.
<- read.csv("https://umich.instructure.com/files/354289/download?download_frd=1", header = FALSE)
Simulation 1:3, ] Simulation[
## V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13
## 1 ID i2 age treat homeless pcs mcs cesd indtot pss_fr drugrisk sexrisk satreat
## 2 1 0 25 0 0 49 7 46 37 0 1 6 0
## 3 2 18 31 0 0 48 34 17 48 0 0 11 0
## V14 V15 V16
## 1 female substance racegrp
## 2 0 cocaine black
## 3 0 alcohol white
To save a data frame to CSV files, we could use the write.csv()
function. The option file = "a/local/file/path"
allow us edit the saved file path.
write.csv(iris, file = "C:/Users/iris.csv")
This example demonstrates data import from a compressed (ZIP) SPSS (SAV) file. In this case, we utilize DSPA Case-Study 25: National Ambulatory Medical Care Survey (NAMCS).
# install.packages("foreign")
library("foreign")
<- tempfile()
pathToZip download.file("https://umich.instructure.com/files/8111611/download?download_frd=1", pathToZip, mode = "wb")
<- read.spss(unzip(pathToZip, files = "namcs2015-spss.sav", list = F, overwrite = TRUE), to.data.frame=TRUE)
dataset dim(dataset)
## [1] 28332 1096
## [1] 28332 1096
# str(dataset)
# View(dataset)
unlink(pathToZip)
We can use the command str()
to explore the structure of a dataset.
str(water)
## 'data.frame': 3331 obs. of 6 variables:
## $ year : int 1990 1990 1990 1990 1990 1990 1990 1990 1990 1990 ...
## $ region : chr "Africa" "Africa" "Africa" "Africa" ...
## $ country : chr "Algeria" "Angola" "Benin" "Botswana" ...
## $ residence_area : chr "Rural" "Rural" "Rural" "Rural" ...
## $ improved_water : num 88 42 49 86 39 67 34 46 37 83 ...
## $ sanitation_facilities: num 77 7 0 22 2 42 27 12 4 11 ...
We can see that this World Drinking Water
dataset has 3331 observations and 6 variables. The output also includes the class of each variable and first few elements in the variable.
Summary statistics for numeric variables in the dataset could be accessed by using the command summary()
.
library(plotly)
## Loading required package: ggplot2
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
summary(water$year)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1990 1995 2005 2002 2010 2012
summary(water[c("improved_water", "sanitation_facilities")])
## improved_water sanitation_facilities
## Min. : 3.0 Min. : 0.00
## 1st Qu.: 77.0 1st Qu.: 42.00
## Median : 93.0 Median : 81.00
## Mean : 84.9 Mean : 68.87
## 3rd Qu.: 99.0 3rd Qu.: 97.00
## Max. :100.0 Max. :100.00
## NA's :32 NA's :135
plot(density(water$improved_water,na.rm = T)) # no need to be continuous, we can still get intuition about the variable distribution
<- density(as.numeric(water$improved_water),na.rm = T)
fit plot_ly(x = fit$x, y = fit$y, type = "scatter", mode = "lines",
fill = "tozeroy", name = "Density") %>%
layout(title='Density of (%) Improved Water Quality',
xaxis = list (title = 'Percent'), yaxis = list (title = 'Density'))
The six summary statistics and NA
’s (missing data) are reported in the output.
Mean and median are two frequent measurements of the central tendency. Mean is “the sum of all values divided by the number of values”. Median is the number in the middle of an ordered list of values. In R, mean()
and median()
functions can provide us with these two measurements.
<-c(40, 56, 99)
vec1mean(vec1)
## [1] 65
mean(c(40, 56, 99))
## [1] 65
median(vec1)
## [1] 56
median(c(40, 56, 99))
## [1] 56
# install.packages("psych");
library("psych")
##
## Attaching package: 'psych'
## The following objects are masked from 'package:ggplot2':
##
## %+%, alpha
geometric.mean(vec1, na.rm=TRUE)
## [1] 60.52866
The mode is the value that occurs most often in the dataset. It is often used in categorical data, where mean and median are inappropriate measurements.
We can have one or more modes. In the water dataset, we have “Europe” and “Urban” as the modes for region and residence area respectively. These two variables are unimodal, which has a single mode. For the year variable, we have two modes 2000 and 2005. Both of the categories have 570 counts. The year variable is an example of a bimodal. We also have multimodal that has two or more modes in the data.
Mode is one of the measures for the central tendency. The best way to use it is to comparing the counts of the mode to other values. This help us to judge whether one or several categories dominates all others in the data. After that, we are able to analyze the story behind these common ones.
In numeric datasets, we could think mode as the highest bin in the histogram, since it is unlikely to have many repeated measurements for continuous variables. In this way, we can also examine if the numeric data is multimodal.
More information about measures of centrality is available here.
The five-number summary describes the spread of a dataset. They are:
Min.
), representing the smallest value in the data1st Qu.
), representing the \(25^{th}\) percentile, which splits off the lowest 25% of data from the highest 75%Median
), representing the \(50^{th}\) percentile, which splits off the lowest 50% of data from the top 50%3rd Qu.
), representing the \(75^{th}\) percentile, which splits off the lowest 75% of data from the top 25%Max.
), representing the largest value in the data.Min
and Max
can be obtained by using min()
and max()
respectively.
The difference between maximum and minimum is known as range. In R, range()
function give us both the minimum and maximum. An combination of range()
and diff()
could do the trick of getting the actual range value.
range(water$year)
## [1] 1990 2012
diff(range(water$year))
## [1] 22
Q1 and Q3 are the 25th and 75th percentiles of the data. Median (Q2) is right in the middle of Q1 and Q3. The difference between Q3 and Q1 is called the interquartile range (IQR). Within the IQR lies half of our data that has no extreme values.
In R, we use the IQR()
to calculate the interquartile range. If we use IQR()
for a data with NA
’s, the NA
’s are ignored by the function while using the option na.rm=TRUE
.
IQR(water$year)
## [1] 15
summary(water$improved_water)
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## 3.0 77.0 93.0 84.9 99.0 100.0 32
IQR(water$improved_water, na.rm = T)
## [1] 22
Just like the command summary()
that we have talked about earlier in this chapter. A similar function quantile()
could be used to obtain the five-number summary.
quantile(water$improved_water, na.rm = T)
## 0% 25% 50% 75% 100%
## 3 77 93 99 100
We can also calculate specific percentiles in the data. For example, if we want the 20th and 60th percentiles, we can do the following.
quantile(water$improved_water, probs = c(0.2, 0.6), na.rm = T)
## 20% 60%
## 71 97
When we include the seq()
function, generating percentiles of evenly-spaced values is available.
quantile(water$improved_water, seq(from=0, to=1, by=0.2), na.rm = T)
## 0% 20% 40% 60% 80% 100%
## 3 71 89 97 100 100
Let’s re-examine the five-number summary for the improved_water
variable. When we ignore the NA
’s, the difference between minimum and Q1 is 74 while the difference between Q3 and maximum is only 1. The interquartile range is 22%. Combining these facts, the first quarter is more widely spread than the middle 50 percent of values. The last quarter is the most condensed one that has only two percentages 99% and 100%. Also, we can notice that the mean is smaller than the median. The mean is more sensitive to the extreme values than the median. We have a very small minimum that makes the range of first quantile very large. This extreme value impacts the mean less than the median.
We can visualize the five-number summary by a boxplot (box-and-whiskers plot). With the boxplot()
function we can manage the title (main=""
) and labels for x (xlab=""
) and y (ylab=""
) axis.
#boxplot(water$improved_water, main="Boxplot for Percent improved_water", ylab="Percentage")
plot_ly(y = ~water$improved_water, type = "box", name="improved water qual") %>%
add_trace(y = ~water$sanitation_facilities, name ="sanitation") %>%
layout(title='Boxplots of Improved Water Quality and Sanitation Facilities',
yaxis = list (title = 'Percent'))
## Warning: Ignoring 32 observations
## Warning: Ignoring 135 observations
In the boxplot we have five horizontal lines each represents the corresponding value in the five-number summary. The box in the middle represents the middle 50 percent of values. The bold line in the box is the median. Mean value is not illustrated on the graph.
Boxplots only allow the two ends to extend to a minimum or maximum of 1.5 times the IQR. Therefore, any value that falls outside of the \(3\times IQR\) range will be represented as circles or dots. They are considered outliers. We can see that there are a lot of outliers with small values on the low ends of the graph.
Histogram is another way to show the spread of a numeric variable, see Chapter 3 for additional information). It uses predetermined number of bins as containers for values to divide the original data. The height of the bins indicates frequency.
# hist(water$improved_water, main = "Histogram of Percent improved_water", xlab="Percentage")
# hist(water$sanitation_facilities, main = "Histogram of Percent sanitation_facilities", xlab = "Percentage")
plot_ly(x = ~water$improved_water, type = "histogram", name="improved_water") %>%
add_trace(x = ~water$sanitation_facilities, type = "histogram", name="sanitation_facilities") %>%
layout(bargap=0.1, title='Histograms', legend = list(orientation = 'h'),
xaxis = list(title = 'Percent'), yaxis = list (title = 'Frequency'))
## Warning: Ignoring 32 observations
## Warning: Ignoring 135 observations
We could see that the shape of two graphs are somewhat similar. They are both left skewed patterns (\(mean \lt median\)). Other common skew patterns are shown in the following picture.
<- 10000
N <- rnbinom(N, 5, 0.1)
x # hist(x,
# xlim=c(min(x), max(x)), probability=T, nclass=max(x)-min(x)+1,
# col='lightblue', xlab=' ', ylab=' ', axes=F,
# main='Right Skewed')
# lines(density(x, bw=1), col='red', lwd=3)
<- density(x)
fit
plot_ly(x = x, type = "histogram", name = "Data Histogram") %>%
add_trace(x = fit$x, y = fit$y, type = "scatter", mode = "lines", opacity=0.3,
fill = "tozeroy", yaxis = "y2", name = "Density (rnbinom(N, 5, 0.1))") %>%
layout(title='Right Skewed Process', yaxis2 = list(overlaying = "y", side = "right"),
legend = list(orientation = 'h'))
<- 10000
N <- rnorm(N, 15, 3.7)
x # hist(x,
# xlim=c(min(x), max(x)), probability=T, nclass=max(x)-min(x)+1,
# col='lightblue', xlab=' ', ylab=' ', axes=F,
# main='Right Skewed')
# lines(density(x, bw=1), col='red', lwd=3)
<- density(x)
fit
plot_ly(x = x, type = "histogram", name = "Data Histogram") %>%
add_trace(x = fit$x, y = fit$y, type = "scatter", mode = "lines", opacity=0.3,
fill = "tozeroy", yaxis = "y2", name = "Density (rnorm(N, 15, 3.7))") %>%
layout(title='Symmetric Process', yaxis2 = list(overlaying = "y", side = "right"),
legend = list(orientation = 'h'))
You can learn more about Probability Distributions in the SOCR EBook and see the density plots of over 80 different probability distributions using the SOCR Java Distribution Calculators or the Distributome HTML5 Distribution Calculators.
For each probability distribution defined in R, there are four functions that provide the density (e.g., dnorm
), the cumulative probability (e.g., pnorm
), the inverse cumulative distribution (quantile) function (e.g., qnorm
), and the random sampling (simulation) function (e.g., rnorm
). The plots below show the standard normal density, cumulative probability and the quantile functions. As the density is very small outside of the interval \((-4,4)\), the plots are restricted to this domain.
<-seq(-4, 4, 0.1) # points from -4 to 4 in 0.1 steps
z<-seq(0.001, 0.999, 0.001) # probability quantile values from 0.1% to 99.9% in 0.1% steps
q
<- data.frame(Z=z, Density=dnorm(z, mean=0, sd=1), Distribution=pnorm(z, mean=0, sd=1))
dStandardNormal
<- data.frame(Q=q, Quantile=qnorm(q, mean=0, sd=1))
qStandardNormal head(dStandardNormal)
## Z Density Distribution
## 1 -4.0 0.0001338302 3.167124e-05
## 2 -3.9 0.0001986555 4.809634e-05
## 3 -3.8 0.0002919469 7.234804e-05
## 4 -3.7 0.0004247803 1.077997e-04
## 5 -3.6 0.0006119019 1.591086e-04
## 6 -3.5 0.0008726827 2.326291e-04
# plot(z, dStandardNormal$Density, main="Normal Density Curve", type = "l", xlab = "critical values", ylab="density", lwd=4, col="blue")
# polygon(z, dStandardNormal$Density, col="red", border="blue")
# plot(z, dStandardNormal$Distribution, main="Normal Distribution", type = "l", xlab = "critical values", ylab="Cumulative Distribution", lwd=4, col="blue")
# plot(q, qStandardNormal$Quantile, main="Normal Quantile Function (Inverse CDF)", type = "l", xlab = "p-values", ylab="Critical Values", lwd=4, col="blue")
plot_ly(x = z, y= dStandardNormal$Density, name = "Normal Density Curve",
mode = 'lines') %>%
layout(title='Normal Density Curve',
xaxis = list(title = 'critical values'),
yaxis = list(title ="Density"),
legend = list(orientation = 'h'))
## No trace type specified:
## Based on info supplied, a 'scatter' trace seems appropriate.
## Read more about this trace type -> https://plotly.com/r/reference/#scatter
plot_ly(x = z, y= dStandardNormal$Distribution,
name = "Normal Density Curve", mode = 'lines') %>%
layout(title='Normal Distribution',
xaxis = list(title = 'critical values'),
yaxis = list(title ="Cumulative Distribution"),
legend = list(orientation = 'h'))
## No trace type specified:
## Based on info supplied, a 'scatter' trace seems appropriate.
## Read more about this trace type -> https://plotly.com/r/reference/#scatter
plot_ly(x = q, y= qStandardNormal$Quantile,
name = "Normal Quantile Function (Inverse CDF)", mode = 'lines') %>%
layout(title='Normal Distribution',
xaxis = list(title = 'probability values'),
yaxis = list(title ="Critical Values"),
legend = list(orientation = 'h'))
## No trace type specified:
## Based on info supplied, a 'scatter' trace seems appropriate.
## Read more about this trace type -> https://plotly.com/r/reference/#scatter
If the data follows a uniform distribution, then all values are equally likely to occur. The histogram for a uniformly distributed data would have equal heights for each bin like the following graph.
## Warning: 'scatter' objects don't have these attributes: 'histnorm'
## Valid attributes include:
## 'type', 'visible', 'showlegend', 'legendgroup', 'opacity', 'name', 'uid', 'ids', 'customdata', 'meta', 'selectedpoints', 'hoverinfo', 'hoverlabel', 'stream', 'transforms', 'uirevision', 'x', 'x0', 'dx', 'y', 'y0', 'dy', 'xperiod', 'yperiod', 'xperiod0', 'yperiod0', 'xperiodalignment', 'yperiodalignment', 'stackgroup', 'orientation', 'groupnorm', 'stackgaps', 'text', 'texttemplate', 'hovertext', 'mode', 'hoveron', 'hovertemplate', 'line', 'connectgaps', 'cliponaxis', 'fill', 'fillcolor', 'marker', 'selected', 'unselected', 'textposition', 'textfont', 'r', 't', 'error_x', 'error_y', 'xcalendar', 'ycalendar', 'xaxis', 'yaxis', 'idssrc', 'customdatasrc', 'metasrc', 'hoverinfosrc', 'xsrc', 'ysrc', 'textsrc', 'texttemplatesrc', 'hovertextsrc', 'hovertemplatesrc', 'textpositionsrc', 'rsrc', 'tsrc', 'key', 'set', 'frame', 'transforms', '_isNestedKey', '_isSimpleKey', '_isGraticule', '_bbox'
Often, but not always, real world processes may appear as normally distributed data. A normal distribution would have a higher frequency for middle values and lower frequency for more extreme values. It has a symmetric and bell-curved shape just like the following diagram generated by R. Many parametric-based statistical approaches assume normality of the data. In cases where this parametric assumption is violated, variable transformations or distribution-free tests may be more appropriate.
<- 1000
N<- rnorm(N, 0, 1)
norm # hist(x, probability=T,
# col='lightblue', xlab=' ', ylab=' ', axes=F,
# main='Normal Distribution')
# lines(density(x, bw=0.4), col='red', lwd=3)
<- density(norm, bw=0.5)
normDensity <- data.frame(x = normDensity$x, y = normDensity$y)
dens <- 0
miny <- max(dens$y)
maxy
plot_ly(dens) %>%
add_histogram(x = norm, name="Normal Histogram") %>%
add_lines(data = dens, x = ~x, y = ~y, yaxis = "y2",
line = list(width = 3), name="N(0,1)") %>%
layout(bargap=0.1, yaxis2 = list(overlaying = "y", side = "right",
range = c(miny, maxy), showgrid = F, zeroline = F),
legend = list(orientation = 'h'), title="Normal(0,1)")
Distribution is a great way to characterize data using only a few parameters. For example, normal distribution can be defined by only two parameters center and spread or statistically mean and standard deviation.
The way to get mean value is to divide the sum of the data values by the number of values. So, we have the following formula.
\[Mean(X)=\mu=\frac{1}{n}\sum_{i=1}^{n} x_i\]
The standard deviation is the square root of the variance. Variance is the average sum of square.
\[Var(X)=\sigma^2=\frac{1}{n-1}\sum^{n}_{i=1} (x_i-\mu)^2\] \[StdDev(X)=\sigma=\sqrt{Var(X)}\]
Since the water dataset is non-normal, we use a new dataset about the demographics of baseball players to illustrate normal distribution properties. The "01_data.txt"
in our class file has following variables:
We check the histogram for approximate normality first.
<-read.table("https://umich.instructure.com/files/330381/download?download_frd=1", header=T)
baseball# hist(baseball$Weight, main = "Histogram for Baseball Player's Weight", xlab="weight")
# hist(baseball$Height, main = "Histogram for Baseball Player's Height", xlab="height")
plot_ly(x = ~baseball$Weight, type = "histogram", name="Baseball Weight", showlegend = F) %>%
layout(bargap=0.1, title='Baseball Weight')
plot_ly(x = ~baseball$Height, type = "histogram", name="Baseball Height", showlegend = F) %>%
layout(bargap=0.1, title='Baseball Height')
This plot allows us to visually inspect the normality of the players height and weight. We could also obtain mean and standard deviation of the weight and height variables.
mean(baseball$Weight)
## [1] 201.7166
mean(baseball$Height)
## [1] 73.69729
var(baseball$Weight)
## [1] 440.9913
sd(baseball$Weight)
## [1] 20.99979
var(baseball$Height)
## [1] 5.316798
sd(baseball$Height)
## [1] 2.305818
Larger standard deviation, or variance, suggest the data is more spread out from the mean. Therefore, the weight variable is more spread than the height variable.
Given the first two moments (mean and standard deviation), we can easily estimate how extreme a specific value is. Assuming we have a normal distribution, the values follow a \(68-95-99.7\) rule. This means 68% of the data lies within the interval \([\mu-\sigma, \mu+\sigma]\);95% of the data lies within the interval \([\mu-2*\sigma, \mu+2*\sigma]\) and 99.7% of the data lies within the interval \([\mu-3*\sigma, \mu+3*\sigma]\). The following graph plotted by R illustrates the \(68-95-99.7\) rule.
<- rnorm(N, 0, 1)
x # hist(x, probability=T,
# col='lightblue', xlab=' ', ylab=' ', axes = F,
# main='68-95-99.7 Rule')
# lines(density(x, bw=0.4), col='red', lwd=3)
# axis(1, at=c(-3, -2, -1, 0, 1, 2, 3), labels = expression(mu-3*sigma, mu-2*sigma, mu-sigma, mu, mu+sigma, mu+2*sigma, mu+3*sigma))
# abline(v=-1, lwd=3, lty=2)
# abline(v=1, lwd=3, lty=2)
# abline(v=-2, lwd=3, lty=2)
# abline(v=2, lwd=3, lty=2)
# abline(v=-3, lwd=3, lty=2)
# abline(v=3, lwd=3, lty=2)
# text(0, 0.2, "68%")
# segments(-1, 0.2, -0.3, 0.2, col = 'red', lwd=2)
# segments(1, 0.2, 0.3, 0.2, col = 'red', lwd=2)
# text(0, 0.15, "95%")
# segments(-2, 0.15, -0.3, 0.15, col = 'red', lwd=2)
# segments(2, 0.15, 0.3, 0.15, col = 'red', lwd=2)
# text(0, 0.1, "99.7%")
# segments(-3, 0.1, -0.3, 0.1, col = 'red', lwd=2)
# segments(3, 0.1, 0.3, 0.1, col = 'red', lwd=2)
<- c("μ-3σ","μ-2σ", "μ-σ", "μ", "μ+σ", "μ+2σ", "μ+3σ")
xLabels <- c("green", "red", "orange", "black", "orange", "red", "green")
labelColors <- c(-3, -2, -1, 0, 1, 2, 3)
xLocation <- 0.2
yLocation <- data.frame(xLabels, xLocation, yLocation)
data
plot_ly(dens) %>%
add_histogram(x = norm, name="Normal Histogram") %>%
add_lines(data = dens, x = ~x, y = ~y+0.05, yaxis = "y2",
line = list(width = 3), name="N(0,1)") %>%
add_annotations(x = ~xLocation, y = ~yLocation, type = 'scatter', ax = 20, ay = 20,
mode = 'text', text = ~xLabels, textposition = 'middle right',
textfont = list(color = labelColors, size = 16)) %>%
add_segments(x=-3, xend=-3, y=0, yend=100, name="99.7%", line=list(dash="dash", color="green")) %>%
add_segments(x=-2, xend=-2, y=0, yend=90, name="95%", line=list(dash="dash", color="red")) %>%
add_segments(x=-1, xend=-1, y=0, yend=80, name="68%", line=list(dash="dash", color="orange")) %>%
add_segments(x=1, xend=1, y=0, yend=80, name="68%", line = list(dash = "dash", color="orange")) %>%
add_segments(x=2, xend=2, y=0, yend=90, name="95%", line=list(dash="dash", color="red")) %>%
add_segments(x=3, xend=3, y=0, yend=100, name="99.7%", line=list(dash="dash", color="green")) %>%
add_segments(x=-3, xend=3, y=100, yend=100, name="99.7%", line=list(dash="dash", color="green")) %>%
add_segments(x=-2, xend=2, y=90, yend=90, name="95%", line=list(dash="dash", color="red")) %>%
add_segments(x=-1, xend=1, y=80, yend=80, name="68%", line=list(dash="dash", color="orange")) %>%
layout(bargap=0.1, xaxis=list(name=""), yaxis=list(title="density/frequency"),
yaxis2 = list(overlaying = "y", side = "right", # title="prob",
range = c(miny, maxy+0.1), showgrid = F, zeroline = F),
legend = list(orientation = 'h'), title="Normal 68-95-99.7% Rule")
Applying the 68-95-99.7 rule to our baseball weight variable, we know that 68% of our players weighted between 180.7168 pounds and 222.7164 pounds; 95% of the players weighted between 159.7170 pounds and 243.7162 pounds; And 99.7% of the players weighted between 138.7172 pounds and 264.7160 pounds.
Back to our water dataset, we can treat the year variable as categorical rather than a numeric variable. Since the year variable only have six distinctive values, it is rational to treat it as a categorical variable where each value is a category that could apply to multiple WHO regions. Moreover, region and residence area variables are also categorical.
Different from numeric variables, the categorical variables are better examined by tables rather than summary statistics. One-way table represents a single categorical variable. It gives us the counts of different categories. table()
function can create one-way tables for our water dataset:
<- read.csv('https://umich.instructure.com/files/399172/download?download_frd=1', header=T)
water
colnames(water)<-c("year", "region", "country", "residence_area", "improved_water", "sanitation_facilities")
table(water$year)
##
## 1990 1995 2000 2005 2010 2012
## 520 561 570 570 556 554
table(water$region)
##
## Africa Americas Eastern Mediterranean
## 797 613 373
## Europe South-East Asia Western Pacific
## 910 191 447
table(water$residence_area)
##
## Rural Total Urban
## 1095 1109 1127
Given that we have a total of 3331 observations, the WHO region table tells us that about 27% (910/3331) of the areas examined in the study are in Europe.
R can directly give us table proportions when using the prop.table()
function. The proportion values can be transformed into percentage form and edit number of digits.
<-table(water$year)
year_tableprop.table(year_table)
##
## 1990 1995 2000 2005 2010 2012
## 0.1561093 0.1684179 0.1711198 0.1711198 0.1669168 0.1663164
<-prop.table(year_table)*100
year_pctround(year_pct, digits=1)
##
## 1990 1995 2000 2005 2010 2012
## 15.6 16.8 17.1 17.1 16.7 16.6
So far the methods and statistics that we have go through are at univariate level. Sometimes we want to examine the relationship between two or multiple variables. For example, did the percentage of population that uses improved drinking-water sources increase over time? To address these problems we need to look at bivariate or multivariate relationships.
Visualizing Relationships - scatterplots
Let’s look at bivariate case first. A scatterplot is a good way to visualize bivariate relationships. We have x axis and y axis each representing one of the variables. Each observation is illustrated on the graph by a dot. If the graph shows a clear pattern rather a group of messy dots or a horizontal line, the two variables may correlated with each other.
In R we can use plot()
function to create scatterplots. We have to define the variables for x-axis and y-axis. The labels in the graph are editable.
# plot.window(c(400,1000), c(500,1000))
# plot(x=water$year, y=water$improved_water,
# main= "Scatterplot of Year vs. Improved_water",
# xlab= "Year",
# ylab= "Percent of Population Using Improved Water")
plot_ly(x = ~water$sanitation_facilities, y = ~water$improved_water, type = "scatter",
mode = "markers") %>%
layout(title='Scatterplot: Improved Water Quality vs. Sanitation Facilities',
xaxis = list (title = 'Water Quality'), yaxis = list (title = 'Sanitation'))
## Warning: Ignoring 167 observations
We can see from the scatterplot that there is an increasing pattern. In later years, the percentages are more centered around one hundred. Especially, in 2012, not of the regions had less than 20% of people using improved water sources while there used to be some regions that have such low percentages in the early years.
Examining Relationships - two-way cross-tabulations
Scatterplot is a useful tool to examine the relationship between two variables where at least one of them is numeric. When both variables are nominal, two-way cross-tabulation would be a better choice (also named as crosstab or contingency table).
The function CrossTable()
is available in R under the package gmodels
. Let’s install it first.
#install.packages("gmodels", repos = "http://cran.us.r-project.org")
library(gmodels)
We are interested in investigating the relationship between WHO region and residence area type in the water study. We might want to know if there is a difference in terms of residence area type between the African WHO region and all other WHO regions.
To address this problem we need to create an indicator variable for African WHO region first.
$africa<-water$region=="Africa" water
Let’s revisit the table()
function to see how many WHO regions are in Africa.
table(water$africa)
##
## FALSE TRUE
## 2534 797
Now, let’s create a two-way cross-tabulation using CrossTable()
.
CrossTable(x=water$residence_area, y=water$africa)
##
##
## Cell Contents
## |-------------------------|
## | N |
## | Chi-square contribution |
## | N / Row Total |
## | N / Col Total |
## | N / Table Total |
## |-------------------------|
##
##
## Total Observations in Table: 3331
##
##
## | water$africa
## water$residence_area | FALSE | TRUE | Row Total |
## ---------------------|-----------|-----------|-----------|
## Rural | 828 | 267 | 1095 |
## | 0.030 | 0.096 | |
## | 0.756 | 0.244 | 0.329 |
## | 0.327 | 0.335 | |
## | 0.249 | 0.080 | |
## ---------------------|-----------|-----------|-----------|
## Total | 845 | 264 | 1109 |
## | 0.002 | 0.007 | |
## | 0.762 | 0.238 | 0.333 |
## | 0.333 | 0.331 | |
## | 0.254 | 0.079 | |
## ---------------------|-----------|-----------|-----------|
## Urban | 861 | 266 | 1127 |
## | 0.016 | 0.050 | |
## | 0.764 | 0.236 | 0.338 |
## | 0.340 | 0.334 | |
## | 0.258 | 0.080 | |
## ---------------------|-----------|-----------|-----------|
## Column Total | 2534 | 797 | 3331 |
## | 0.761 | 0.239 | |
## ---------------------|-----------|-----------|-----------|
##
##
Each cell in the table contains five numbers. The first one N give us the count that falls into its corresponding category. The Chi-square contribution provide us information about the cell’s contribution in the Pearson’s Chi-squared test for independence between two variables. This number measures the probability that the differences in cell counts are due to chance alone.
The number of most interest is the N/ Col Total
or the counts over column total. In this case, these numbers represent the distribution for residence area type among African regions and the regions in the rest of the world. We can see the numbers are very close between African and non-African regions for each type of residence area. Therefore, we can conclude that African WHO regions do not have a difference in terms of residence area types compared to the rest of the world.
In the previous sections, we simply ignored the incomplete observations in our water dataset (na.rm = TRUE
). Is this an appropriate strategy to handle incomplete data? Could the missingness pattern of those incomplete observations be important? It is possible that the arrangement of the missing observations may reflect an important factor that was not accounted for in our statistics or our models.
Missing Completely at Random (MCAR) is an assumption about the probability of missingness being equal for all cases; Missing at Random (MAR) assumes the probability of missingness has a known but random mechanism (e.g., different rates for different groups); Missing not at Random (MNAR) suggest a missingness mechanism linked to the values of predictors and/or response, e.g., some participants may drop out of a drug trial when they have side-effects.
There are a number of strategies to impute missing data. The expectation maximization (EM) algorithm provides one example for handling missing data. The SOCR EM tutorial, activity, and documentations provides the theory, applications and practice for effective (multidimensional) EM parameter estimation.
The simplest way to handle incomplete data is to substitute each missing value with its (feature or column) average. When the missingness proportion is small, the the effect of substituting the means for the missing values will have little effect on the mean, variance, or other important statistics of the data. Also, this will preserve those non-missing values of the same observation or row.
<-mean(water$improved_water, na.rm = T)
m1<-mean(water$sanitation_facilities, na.rm = T)
m2<-water
water_impfor(i in 1:3331){
if(is.na(water_imp$improved_water[i])){
$improved_water[i]=m1
water_imp
}if(is.na(water_imp$sanitation_facilities[i])){
$sanitation_facilities[i]=m2
water_imp
}
}summary(water_imp)
## year region country residence_area
## Min. :1990 Length:3331 Length:3331 Length:3331
## 1st Qu.:1995 Class :character Class :character Class :character
## Median :2005 Mode :character Mode :character Mode :character
## Mean :2002
## 3rd Qu.:2010
## Max. :2012
## improved_water sanitation_facilities africa
## Min. : 3.0 Min. : 0.00 Mode :logical
## 1st Qu.: 77.0 1st Qu.: 44.00 FALSE:2534
## Median : 93.0 Median : 79.00 TRUE :797
## Mean : 84.9 Mean : 68.87
## 3rd Qu.: 99.0 3rd Qu.: 97.00
## Max. :100.0 Max. :100.00
A more sophisticated way of resolving missing data is to use a model (e.g., linear regression) to predict the missing feature and impute its missing values. This is called the predictive mean matching approach
. This method is good for data with multivariate normality. However, a disadvantage of it is that it can only predict one value at a time, which is very time consuming. Also, the multivariate normality assumption might not be satisfied and there may be important multivariate relations that are not accounted for. We are using the mi
package for the predictive mean matching procedure.
Let’s install the mi
package first.
# install.packages("mi")
library(mi)
Then we need to get the missing information matrix. We are using the imputation method pmm
(predictive mean matching approach) for both missing variables.
<-missing_data.frame(water)
mdfhead(mdf)
## year region country residence_area improved_water sanitation_facilities
## 1 1990 Africa Algeria Rural 88 77
## 2 1990 Africa Angola Rural 42 7
## 3 1990 Africa Benin Rural 49 0
## 4 1990 Africa Botswana Rural 86 22
## 5 1990 Africa Burkina Faso Rural 39 2
## 6 1990 Africa Burundi Rural 67 42
## africa missing_improved_water missing_sanitation_facilities
## 1 TRUE FALSE FALSE
## 2 TRUE FALSE FALSE
## 3 TRUE FALSE FALSE
## 4 TRUE FALSE FALSE
## 5 TRUE FALSE FALSE
## 6 TRUE FALSE FALSE
show(mdf)
## Object of class missing_data.frame with 3331 observations on 7 variables
##
## There are 3 missing data patterns
##
## Append '@patterns' to this missing_data.frame to access the corresponding pattern for every observation or perhaps use table()
##
## type missing method model
## year continuous 0 <NA> <NA>
## region unordered-categorical 0 <NA> <NA>
## country unordered-categorical 0 <NA> <NA>
## residence_area unordered-categorical 0 <NA> <NA>
## improved_water continuous 32 ppd linear
## sanitation_facilities continuous 135 ppd linear
## africa binary 0 <NA> <NA>
##
## family link transformation
## year <NA> <NA> standardize
## region <NA> <NA> <NA>
## country <NA> <NA> <NA>
## residence_area <NA> <NA> <NA>
## improved_water gaussian identity standardize
## sanitation_facilities gaussian identity standardize
## africa <NA> <NA> <NA>
<-change(mdf, y="improved_water", what = "imputation_method", to="pmm")
mdf<-change(mdf, y="sanitation_facilities", what = "imputation_method", to="pmm") mdf
data.frame
to a missing_data.frame
allows us to include in the DF enhanced metadata about each variable, which is essential for the subsequent modeling, interpretation and imputation of the initial missing data.show()
displays all missing variables and their class-labels (e.g., continuous), along with meta-data. The missing_data.frame
constructor suggests the most appropriate classes for each missing variable, however, the user often needs to correct, modify or change these meta-data, using change()
.change()
function to change/correct many meta-data in the constructed missing_data.frame
object which are incorrect when using show(mfd)
.summary
, image
, or hist
of the missing_data.frame.We can perform the initial imputation. Here we imputed 3 times, which will create 3 different datasets with slightly different imputed values.
<-mi(mdf, n.iter=10, n.chains=3, verbose=T) imputations
Next, we need to extract several multiply imputed data.frames
from imputations
object. Finally, we can compare the summary stats between the original dataset and the imputed datasets.
library(mi)
<- complete(imputations, 3)
data.frames summary(water)
## year region country residence_area
## Min. :1990 Length:3331 Length:3331 Length:3331
## 1st Qu.:1995 Class :character Class :character Class :character
## Median :2005 Mode :character Mode :character Mode :character
## Mean :2002
## 3rd Qu.:2010
## Max. :2012
##
## improved_water sanitation_facilities africa
## Min. : 3.0 Min. : 0.00 Mode :logical
## 1st Qu.: 77.0 1st Qu.: 42.00 FALSE:2534
## Median : 93.0 Median : 81.00 TRUE :797
## Mean : 84.9 Mean : 68.87
## 3rd Qu.: 99.0 3rd Qu.: 97.00
## Max. :100.0 Max. :100.00
## NA's :32 NA's :135
summary(data.frames[[1]])
## year region country
## Min. :1990 Africa :797 Albania : 18
## 1st Qu.:1995 Americas :613 Algeria : 18
## Median :2005 Eastern Mediterranean:373 Andorra : 18
## Mean :2002 Europe :910 Angola : 18
## 3rd Qu.:2010 South-East Asia :191 Antigua and Barbuda: 18
## Max. :2012 Western Pacific :447 Argentina : 18
## (Other) :3223
## residence_area improved_water sanitation_facilities africa
## Rural:1095 Min. : 3.00 Min. : 0.00 FALSE:2534
## Total:1109 1st Qu.: 77.00 1st Qu.: 43.00 TRUE : 797
## Urban:1127 Median : 93.00 Median : 81.00
## Mean : 84.84 Mean : 69.33
## 3rd Qu.: 99.00 3rd Qu.: 97.00
## Max. :100.00 Max. :100.00
##
## missing_improved_water missing_sanitation_facilities
## Mode :logical Mode :logical
## FALSE:3299 FALSE:3196
## TRUE :32 TRUE :135
##
##
##
##
<- lapply(data.frames, summary)
mySummary $`chain:1` # report just the summary of the first chain. mySummary
## year region country
## Min. :1990 Africa :797 Albania : 18
## 1st Qu.:1995 Americas :613 Algeria : 18
## Median :2005 Eastern Mediterranean:373 Andorra : 18
## Mean :2002 Europe :910 Angola : 18
## 3rd Qu.:2010 South-East Asia :191 Antigua and Barbuda: 18
## Max. :2012 Western Pacific :447 Argentina : 18
## (Other) :3223
## residence_area improved_water sanitation_facilities africa
## Rural:1095 Min. : 3.00 Min. : 0.00 FALSE:2534
## Total:1109 1st Qu.: 77.00 1st Qu.: 43.00 TRUE : 797
## Urban:1127 Median : 93.00 Median : 81.00
## Mean : 84.84 Mean : 69.33
## 3rd Qu.: 99.00 3rd Qu.: 97.00
## Max. :100.00 Max. :100.00
##
## missing_improved_water missing_sanitation_facilities
## Mode :logical Mode :logical
## FALSE:3299 FALSE:3196
## TRUE :32 TRUE :135
##
##
##
##
This is just a brief introduction for handling incomplete datasets. In later chapters, we will discuss more about missing data with different imputation methods and how to evaluate the complete imputed results.
Suppose we would like to generate a synthetic dataset: \[sim\_data=\{y, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10\}.\]
Then, we can introduce a method that takes a dataset and a desired proportion of missingness and wipes out the same proportion of the data, i.e., introduces random patterns of missingness. Note that there are already R
functions that automate the introduction of missingness, e.g., missForest::prodNA()
, however writing such method from scratch is also useful.
set.seed(123)
# create MCAR missing-data generator
<- function (data, pct.mis = 10)
create.missing
{<- nrow(data)
n <- ncol(data)
J if (length(pct.mis) == 1) {
if(pct.mis>= 0 & pct.mis <=100) {
<- rep((n * (pct.mis/100)), J)
n.mis
}else {
warning("Percent missing values should be an integer between 0 and 100! Exiting"); break
}
}else {
if (length(pct.mis) < J)
stop("The length of the missing-vector is not equal to the number of columns in the data! Exiting!")
<- n * (pct.mis/100)
n.mis
}for (i in 1:ncol(data)) {
if (n.mis[i] == 0) { # if column has no missing do nothing.
<- data[, i]
data[, i]
}else {
sample(1:n, n.mis[i], replace = FALSE), i] <- NA
data[# For each given column (i), sample the row indices (1:n),
# a number of indices to replace as "missing", n.mis[i], "NA",
# without replacement
}
}return(as.data.frame(data))
}
Next, let’s synthetically generate (simulate) \(1,000\) cases including all 11 features in the data (\(\{y, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10\}\)).
<- 1000; u1 <- rbinom(n, 1, .5); v1 <- log(rnorm(n, 5, 1)); x1 <- u1*exp(v1)
n <- rbinom(n, 1, .5); v2 <- log(rnorm(n, 5, 1)); x2 <- u2*exp(v2)
u2 <- rbinom(n, 1, prob=0.45); x4 <- ordered(rep(seq(1, 5), n)[sample(1:n, n)]); x5 <- rep(letters[1:10], n)[sample(1:n, n)]; x6 <- trunc(runif(n, 1, 10)); x7 <- rnorm(n); x8 <- factor(rep(seq(1, 10), n)[sample(1:n, n)]); x9 <- runif(n, 0.1, .99); x10 <- rpois(n, 4); y <- x1 + x2 + x7 + x9 + rnorm(n)
x3
# package the simulated data as a data frame object
<- cbind.data.frame(y, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10)
sim_data
# randomly create missing values
<- create.missing(sim_data, pct.mis=30);
sim_data_30pct_missing # head(sim_data_30pct_missing); summary(sim_data_30pct_missing)
# install.packages("DT")
library("DT")
datatable(sim_data)
datatable(sim_data_30pct_missing)
# install.packages("mi")
# install.packages("betareg")
library("betareg"); library("mi")
# get show the missing information matrix
<- missing_data.frame(sim_data_30pct_missing)
mdf # show(mdf)
datatable(mdf)
# mdf@patterns # to get the textual missing pattern
image(mdf) # remember the visual pattern of this MCAR
In the missing data plot above, missing values are illustrated as black
segments in the case-by-feature bivariate chart. The hot
colormap (17-level) represents the normalized values of the corresponding feature-index pairs, see the mi::image() documentation. Also, test the order
, cluster
and grayscale
options, e.g., image(mdf, x.order = T, clustered = F, grayscale =T)
.
The histogram plots display the distributions of:
# Next try to impute the missing values.
# Get the Graph Parameters (plotting canvas/margins)
# set to plot the histograms for the 3 imputation chains
# mfcol=c(nr, nc). Subsequent histograms are drawn as nr-by-nc arrays on the graphics device by columns (mfcol), or rows (mfrow)
# oma
# oma=c(bottom, left, top, right) giving the size of the outer margins in lines of text
# mar=c(bottom, left, top, right) gives the number of lines of margin to be specified on the four sides of the plot.
# tcl=length of tick marks as a fraction of the height of a line of text (default=0.5)
par(mfcol=c(5, 5), oma=c(1, 1, 0, 0), mar=c(1, 1, 1, 0), tcl=-0.1, mgp=c(0, 0, 0))
# Note to get verbose output-report, parallel must be OFF: parallel=FALSE, verbose=TRUE
<- mi(sim_data_30pct_missing, n.iter=5, n.chains=3, verbose=TRUE)
imputations hist(imputations)
# Extracts several multiply imputed data.frames from "imputations" object
<- complete(imputations, 3)
data.frames
# compare the 3 objects, sim_data, sim_data_30pct_missing, and imputed chain1
datatable(sim_data, caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;','Table: Initial sim_data'))
datatable(sim_data_30pct_missing, caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: sim_data_30pct_missing'))
datatable(data.frames[[1]], caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: Imputed data (chain 1)'))
# Compare the summary stats for the original data (prior to introducing missing
# values) with missing data and the re-completed data following imputation
# summary(sim_data)
datatable(data.frame(t(as.matrix(unclass(summary(sim_data)))), check.names = FALSE, stringsAsFactors = FALSE), caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: summary(sim_data)'))
<- lapply(data.frames, summary)
mySummary datatable(data.frame(t(as.matrix(unclass(mySummary$`chain:1`))), check.names = FALSE, stringsAsFactors = FALSE), caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: Imputed data: summary(chain:1)'))
Let’s check imputation convergence (details provided below).
round(mipply(imputations, mean, to.matrix = TRUE), 3)
## chain:1 chain:2 chain:3
## y 0.015 0.004 0.019
## x1 -0.001 -0.011 -0.011
## x2 -0.020 -0.015 -0.028
## x3 1.434 1.393 1.427
## x4 2.972 2.939 2.912
## x5 5.620 5.639 5.557
## x6 -0.003 -0.008 0.001
## x7 -0.003 0.005 0.014
## x8 5.390 5.422 5.415
## x9 0.532 0.531 0.530
## x10 -0.007 0.011 0.006
## missing_y 0.300 0.300 0.300
## missing_x1 0.300 0.300 0.300
## missing_x2 0.300 0.300 0.300
## missing_x3 0.300 0.300 0.300
## missing_x4 0.300 0.300 0.300
## missing_x5 0.300 0.300 0.300
## missing_x6 0.300 0.300 0.300
## missing_x7 0.300 0.300 0.300
## missing_x8 0.300 0.300 0.300
## missing_x9 0.300 0.300 0.300
## missing_x10 0.300 0.300 0.300
Rhats(imputations, statistic = "moments") # assess the convergence of MI algorithm
## mean_y mean_x1 mean_x2 mean_x3 mean_x4 mean_x5 mean_x6 mean_x7
## 1.6250840 1.0383195 0.9782508 0.9840321 0.9657574 0.9937716 0.9458068 1.1694842
## mean_x8 mean_x9 mean_x10 sd_y sd_x1 sd_x2 sd_x3 sd_x4
## 0.9842273 1.0889008 0.9354927 0.9756234 1.1774772 0.9743532 0.9797381 1.0203606
## sd_x5 sd_x6 sd_x7 sd_x8 sd_x9 sd_x10
## 1.0155219 0.9182896 1.1398756 1.2472042 1.0411495 1.0962671
plot(imputations); hist(imputations); image(imputations); summary(imputations)
## $y
## $y$is_missing
## missing
## FALSE TRUE
## 700 300
##
## $y$imputed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -1.41577 -0.33398 0.03593 0.04220 0.40369 1.39508
##
## $y$observed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -1.194077 -0.395670 0.001664 0.000000 0.347725 1.423707
##
##
## $x1
## $x1$is_missing
## missing
## FALSE TRUE
## 700 300
##
## $x1$imputed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -1.67869 -0.39314 -0.03534 -0.02669 0.31931 1.48666
##
## $x1$observed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -0.4805 -0.4805 -0.4805 0.0000 0.4817 1.1365
##
##
## $x2
## $x2$is_missing
## missing
## FALSE TRUE
## 700 300
##
## $x2$imputed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -1.57081 -0.43297 -0.09756 -0.06952 0.26401 1.57792
##
## $x2$observed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -0.48420 -0.48420 0.01595 0.00000 0.47667 1.14717
##
##
## $x3
## $x3$crosstab
##
## observed imputed
## 0 1215 531
## 1 885 369
##
##
## $x4
## $x4$crosstab
##
## observed imputed
## 1 408 226
## 2 429 182
## 3 438 182
## 4 411 157
## 5 414 153
##
##
## $x5
## $x5$crosstab
##
## observed imputed
## a 186 80
## b 210 96
## c 195 68
## d 231 100
## e 198 92
## f 219 94
## g 210 77
## h 219 101
## i 216 96
## j 216 96
##
##
## $x6
## $x6$is_missing
## missing
## FALSE TRUE
## 700 300
##
## $x6$imputed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -1.690189 -0.336986 -0.005972 -0.011136 0.333502 1.760024
##
## $x6$observed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -0.81073 -0.41317 -0.01562 0.00000 0.38194 0.77949
##
##
## $x7
## $x7$is_missing
## missing
## FALSE TRUE
## 700 300
##
## $x7$imputed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -1.668015 -0.325676 0.003431 0.018537 0.365321 1.705244
##
## $x7$observed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -1.576156 -0.336879 0.003784 0.000000 0.369404 1.773350
##
##
## $x8
## $x8$crosstab
##
## observed imputed
## 1 213 115
## 2 222 97
## 3 186 86
## 4 210 91
## 5 228 92
## 6 219 82
## 7 210 80
## 8 207 91
## 9 198 91
## 10 207 75
##
##
## $x9
## $x9$is_missing
## missing
## FALSE TRUE
## 700 300
##
## $x9$imputed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.004684 0.341643 0.542036 0.536305 0.749023 0.998983
##
## $x9$observed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 0.1010 0.3077 0.5100 0.5286 0.7681 0.9881
##
##
## $x10
## $x10$is_missing
## missing
## FALSE TRUE
## 700 300
##
## $x10$imputed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -1.66587 -0.35833 0.01858 0.01068 0.37425 1.78128
##
## $x10$observed
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## -0.981263 -0.494111 -0.006959 0.000000 0.236617 1.698072
Finally, pool over the \(m = 3\) completed datasets when we fit the “model”. Pool from across the 3 chains - in order to estimate a linear regression model.
<- pool(y ~ x1+x2+x3+x4+x5+x6+x7+x8+x9+x10, data=imputations, m=3)
model_results display (model_results); summary (model_results)
## bayesglm(formula = y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 +
## x9 + x10, data = imputations, m = 3)
## coef.est coef.se
## (Intercept) -0.23 0.84
## x1 0.95 0.03
## x2 0.95 0.03
## x31 0.12 0.28
## x4.L 0.37 0.21
## x4.Q -0.22 0.20
## x4.C -0.11 0.11
## x4^4 0.02 0.27
## x5b -0.36 0.43
## x5c -0.10 0.58
## x5d 0.35 0.56
## x5e 0.70 0.33
## x5f 0.69 0.63
## x5g 0.04 0.53
## x5h 0.82 0.50
## x5i 0.20 0.43
## x5j -0.21 0.54
## x6 0.06 0.05
## x7 0.95 0.17
## x82 0.16 0.29
## x83 -0.10 0.25
## x84 0.25 0.36
## x85 -0.06 0.26
## x86 -0.41 0.46
## x87 -0.25 0.25
## x88 0.00 0.42
## x89 -0.32 0.22
## x810 -0.53 0.69
## x9 1.01 0.52
## x10 0.04 0.05
## n = 970, k = 30
## residual deviance = 2075.2, null deviance = 15274.1 (difference = 13198.9)
## overdispersion parameter = 2.1
## residual sd is sqrt(overdispersion) = 1.46
##
## Call:
## pool(formula = y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 +
## x10, data = imputations, m = 3)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -3.0287 -0.7195 -0.0114 0.7055 3.1935
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.22562 0.83837 -0.269 0.8079
## x1 0.94691 0.02724 34.767 1.00e-08 ***
## x2 0.94659 0.02913 32.494 2.12e-07 ***
## x31 0.12427 0.27533 0.451 0.6871
## x4.L 0.36632 0.21288 1.721 0.1702
## x4.Q -0.21886 0.19982 -1.095 0.3382
## x4.C -0.10605 0.10617 -0.999 0.3181
## x4^4 0.02099 0.26509 0.079 0.9423
## x5b -0.36212 0.43290 -0.836 0.4555
## x5c -0.09886 0.57680 -0.171 0.8757
## x5d 0.35010 0.56095 0.624 0.5813
## x5e 0.69696 0.33094 2.106 0.0773 .
## x5f 0.69342 0.63285 1.096 0.3669
## x5g 0.04300 0.52692 0.082 0.9403
## x5h 0.82361 0.49543 1.662 0.1952
## x5i 0.20160 0.42529 0.474 0.6623
## x5j -0.20533 0.53705 -0.382 0.7293
## x6 0.05626 0.05388 1.044 0.3846
## x7 0.95224 0.17449 5.457 0.0247 *
## x82 0.16359 0.28904 0.566 0.5873
## x83 -0.10486 0.24541 -0.427 0.6720
## x84 0.25045 0.36404 0.688 0.5267
## x85 -0.06344 0.26116 -0.243 0.8117
## x86 -0.40774 0.45624 -0.894 0.4343
## x87 -0.25410 0.25189 -1.009 0.3249
## x88 -0.00232 0.42031 -0.006 0.9959
## x89 -0.31938 0.22427 -1.424 0.1570
## x810 -0.53252 0.69393 -0.767 0.5124
## x9 1.01156 0.51707 1.956 0.1598
## x10 0.03926 0.04751 0.826 0.4626
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for gaussian family taken to be 2.139391)
##
## Null deviance: 15274.1 on 999 degrees of freedom
## Residual deviance: 2075.2 on 970 degrees of freedom
## AIC: 3628
##
## Number of Fisher Scoring iterations: 7
# Report the summaries of the imputations
<- complete(imputations, 3) # extract the first 3 chains
data.frames <-lapply(data.frames, summary)
mySummary
datatable(data.frame(t(as.matrix(unclass(mySummary$`chain:1`))), check.names = FALSE, stringsAsFactors = FALSE), caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: Imputed data: summary(chain:1)'))
datatable(data.frame(t(as.matrix(unclass(mySummary$`chain:2`))), check.names = FALSE, stringsAsFactors = FALSE), caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: Imputed data: summary(chain:2)'))
datatable(data.frame(t(as.matrix(unclass(mySummary$`chain:3`))), check.names = FALSE, stringsAsFactors = FALSE), caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: Imputed data: summary(chain:3)'))
coef(summary(model_results))[, 1:2] # get the model coef's and their SE's
## Estimate Std. Error
## (Intercept) -0.225624726 0.83837132
## x1 0.946912208 0.02723566
## x2 0.946591603 0.02913097
## x31 0.124269459 0.27532628
## x4.L 0.366317025 0.21287669
## x4.Q -0.218863807 0.19981830
## x4.C -0.106051930 0.10616787
## x4^4 0.020986511 0.26508721
## x5b -0.362115428 0.43290099
## x5c -0.098857461 0.57679824
## x5d 0.350104934 0.56094983
## x5e 0.696965330 0.33093801
## x5f 0.693419833 0.63284572
## x5g 0.042998387 0.52691549
## x5h 0.823606634 0.49543030
## x5i 0.201599456 0.42529111
## x5j -0.205328079 0.53704601
## x6 0.056256058 0.05388013
## x7 0.952240066 0.17449343
## x82 0.163588372 0.28904159
## x83 -0.104860861 0.24541487
## x84 0.250449815 0.36403703
## x85 -0.063441772 0.26115767
## x86 -0.407739073 0.45623552
## x87 -0.254099779 0.25189186
## x88 -0.002319526 0.42031155
## x89 -0.319377580 0.22426814
## x810 -0.532518409 0.69392756
## x9 1.011561785 0.51706961
## x10 0.039256915 0.04751091
library("lattice")
densityplot(y ~ x1 + x2, data=imputations)
# plot_ly(imputations@data$`chain:1`, x=~(x1+x2), y=~density(y))
# To compare the density of observed data and imputed data --
# these should be similar (though not identical) under MAR assumption
Notes:
Next, we will see an example using the traumatic brain injury (TBI) dataset. More information about the clinical assesment scores (e.g., EGOS, GCS) is available in this publication (DOI: 10.1080/02699050701727460).
# Load the (raw) data from the table into a plain text file "08_EpiBioSData_Incomplete.csv"
<- read.csv("https://umich.instructure.com/files/720782/download?download_frd=1", na.strings=c("", ".", "NA")) ## 1. read in data
TBI_Data summary(TBI_Data)
## id age sex mechanism
## Min. : 1.00 Min. :16.00 Length:46 Length:46
## 1st Qu.:12.25 1st Qu.:23.00 Class :character Class :character
## Median :23.50 Median :33.00 Mode :character Mode :character
## Mean :23.50 Mean :36.89
## 3rd Qu.:34.75 3rd Qu.:47.25
## Max. :46.00 Max. :83.00
##
## field.gcs er.gcs icu.gcs worst.gcs X6m.gose
## Min. : 3 Min. : 3.000 Min. : 0.000 Min. : 0.0 Min. :2.000
## 1st Qu.: 3 1st Qu.: 4.000 1st Qu.: 3.000 1st Qu.: 3.0 1st Qu.:3.000
## Median : 7 Median : 7.500 Median : 6.000 Median : 3.0 Median :5.000
## Mean : 8 Mean : 8.182 Mean : 6.378 Mean : 5.4 Mean :4.805
## 3rd Qu.:12 3rd Qu.:12.250 3rd Qu.: 8.000 3rd Qu.: 7.0 3rd Qu.:6.000
## Max. :15 Max. :15.000 Max. :14.000 Max. :14.0 Max. :8.000
## NA's :2 NA's :2 NA's :1 NA's :1 NA's :5
## X2013.gose skull.fx temp.injury surgery
## Min. :2.000 Min. :0.0000 Min. :0.000 Min. :0.0000
## 1st Qu.:5.000 1st Qu.:0.0000 1st Qu.:0.000 1st Qu.:0.0000
## Median :7.000 Median :1.0000 Median :1.000 Median :1.0000
## Mean :5.804 Mean :0.6087 Mean :0.587 Mean :0.6304
## 3rd Qu.:7.000 3rd Qu.:1.0000 3rd Qu.:1.000 3rd Qu.:1.0000
## Max. :8.000 Max. :1.0000 Max. :1.000 Max. :1.0000
##
## spikes.hr min.hr max.hr acute.sz
## Min. : 1.280 Min. : 0.000 Min. : 12.00 Min. :0.0000
## 1st Qu.: 5.357 1st Qu.: 0.000 1st Qu.: 35.25 1st Qu.:0.0000
## Median : 18.170 Median : 0.000 Median : 97.50 Median :0.0000
## Mean : 52.872 Mean : 3.571 Mean : 241.89 Mean :0.1739
## 3rd Qu.: 57.227 3rd Qu.: 0.000 3rd Qu.: 312.75 3rd Qu.:0.0000
## Max. :294.000 Max. :42.000 Max. :1199.00 Max. :1.0000
## NA's :18 NA's :18 NA's :18
## late.sz ever.sz
## Min. :0.0000 Min. :0.000
## 1st Qu.:0.0000 1st Qu.:0.000
## Median :1.0000 Median :1.000
## Mean :0.5652 Mean :0.587
## 3rd Qu.:1.0000 3rd Qu.:1.000
## Max. :1.0000 Max. :1.000
##
# Get information matrix of the data
# 2. create an object of class "missing_data.frame" from the data.frame TBI_data
# Convert to a missing_data.frame
# library("betareg"); library("mi")
<- missing_data.frame(TBI_Data) # warnings about missingness patterns mdf
## NOTE: The following pairs of variables appear to have the same missingness pattern.
## Please verify whether they are in fact logically distinct variables.
## [,1] [,2]
## [1,] "icu.gcs" "worst.gcs"
datatable(mdf); mdf@patterns; image(mdf)
## [1] spikes.hr, min.hr, max.hr
## [2] field.gcs
## [3] nothing
## [4] nothing
## [5] nothing
## [6] nothing
## [7] spikes.hr, min.hr, max.hr
## [8] nothing
## [9] nothing
## [10] nothing
## [11] nothing
## [12] nothing
## [13] spikes.hr, min.hr, max.hr
## [14] nothing
## [15] spikes.hr, min.hr, max.hr
## [16] spikes.hr, min.hr, max.hr
## [17] nothing
## [18] spikes.hr, min.hr, max.hr
## [19] spikes.hr, min.hr, max.hr
## [20] spikes.hr, min.hr, max.hr
## [21] X6m.gose, spikes.hr, min.hr, max.hr
## [22] nothing
## [23] spikes.hr, min.hr, max.hr
## [24] spikes.hr, min.hr, max.hr
## [25] spikes.hr, min.hr, max.hr
## [26] spikes.hr, min.hr, max.hr
## [27] spikes.hr, min.hr, max.hr
## [28] X6m.gose
## [29] spikes.hr, min.hr, max.hr
## [30] nothing
## [31] X6m.gose, spikes.hr, min.hr, max.hr
## [32] spikes.hr, min.hr, max.hr
## [33] nothing
## [34] nothing
## [35] nothing
## [36] nothing
## [37] field.gcs, er.gcs, icu.gcs, worst.gcs, X6m.gose
## [38] er.gcs
## [39] nothing
## [40] nothing
## [41] nothing
## [42] spikes.hr, min.hr, max.hr
## [43] nothing
## [44] nothing
## [45] nothing
## [46] X6m.gose
## 7 Levels: nothing field.gcs X6m.gose er.gcs ... field.gcs, er.gcs, icu.gcs, worst.gcs, X6m.gose
# 3. get description of the "family", "imputation_method", "size", "transformation", "type", "link", or "model" of each incomplete variable
# show(mdf)
# 4. change things: mi::change() method changes the family, imputation method,
# size, type, and so forth of a missing variable. It's called
# before calling mi to affect how the conditional expectation of each
# missing variable is modeled.
<- change(mdf, y = "spikes.hr", what = "transformation", to = "identity")
mdf # The "to" choices include "identity" = no transformation, "standardize" = standardization, "log" = natural logarithm transformation, "logshift" = log(y + a) transformation, where a is a small constant, or "sqrt" = square-root variable transformation. Changing the transformation will correspondingly change the inverse transformation.
# 5. examine missingness patterns
summary(mdf); hist(mdf);
## id age sex mechanism
## Min. : 1.00 Min. :16.00 Length:46 Length:46
## 1st Qu.:12.25 1st Qu.:23.00 Class :character Class :character
## Median :23.50 Median :33.00 Mode :character Mode :character
## Mean :23.50 Mean :36.89
## 3rd Qu.:34.75 3rd Qu.:47.25
## Max. :46.00 Max. :83.00
##
## field.gcs er.gcs icu.gcs worst.gcs X6m.gose
## Min. : 3 Min. : 3.000 Min. : 0.000 Min. : 0.0 Min. :2.000
## 1st Qu.: 3 1st Qu.: 4.000 1st Qu.: 3.000 1st Qu.: 3.0 1st Qu.:3.000
## Median : 7 Median : 7.500 Median : 6.000 Median : 3.0 Median :5.000
## Mean : 8 Mean : 8.182 Mean : 6.378 Mean : 5.4 Mean :4.805
## 3rd Qu.:12 3rd Qu.:12.250 3rd Qu.: 8.000 3rd Qu.: 7.0 3rd Qu.:6.000
## Max. :15 Max. :15.000 Max. :14.000 Max. :14.0 Max. :8.000
## NA's :2 NA's :2 NA's :1 NA's :1 NA's :5
## X2013.gose skull.fx temp.injury surgery
## Min. :2.000 Min. :0.0000 Min. :0.000 Min. :0.0000
## 1st Qu.:5.000 1st Qu.:0.0000 1st Qu.:0.000 1st Qu.:0.0000
## Median :7.000 Median :1.0000 Median :1.000 Median :1.0000
## Mean :5.804 Mean :0.6087 Mean :0.587 Mean :0.6304
## 3rd Qu.:7.000 3rd Qu.:1.0000 3rd Qu.:1.000 3rd Qu.:1.0000
## Max. :8.000 Max. :1.0000 Max. :1.000 Max. :1.0000
##
## spikes.hr min.hr max.hr acute.sz
## Min. : 1.280 Min. : 0.000 Min. : 12.00 Min. :0.0000
## 1st Qu.: 5.357 1st Qu.: 0.000 1st Qu.: 35.25 1st Qu.:0.0000
## Median : 18.170 Median : 0.000 Median : 97.50 Median :0.0000
## Mean : 52.872 Mean : 3.571 Mean : 241.89 Mean :0.1739
## 3rd Qu.: 57.227 3rd Qu.: 0.000 3rd Qu.: 312.75 3rd Qu.:0.0000
## Max. :294.000 Max. :42.000 Max. :1199.00 Max. :1.0000
## NA's :18 NA's :18 NA's :18
## late.sz ever.sz
## Min. :0.0000 Min. :0.000
## 1st Qu.:0.0000 1st Qu.:0.000
## Median :1.0000 Median :1.000
## Mean :0.5652 Mean :0.587
## 3rd Qu.:1.0000 3rd Qu.:1.000
## Max. :1.0000 Max. :1.000
##
image(mdf)
# 6. Perform initial imputation
<- mi(mdf, n.iter=10, n.chains=5, verbose=TRUE)
imputations1 hist(imputations1)
# 7. Extracts several multiply imputed data.frames from "imputations" object
<- complete(imputations1, 5)
data.frames1
# 8. Report a list of "summaries" for each element (imputation instance)
<- lapply(data.frames1, summary)
mySummary1
datatable(data.frame(t(as.matrix(unclass(mySummary1$`chain:1`))), check.names = FALSE, stringsAsFactors = FALSE), caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: Imputed data: summary(chain:1)'),
extensions = 'Buttons', options = list(dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print')))
datatable(data.frame(t(as.matrix(unclass(mySummary1$`chain:5`))), check.names = FALSE, stringsAsFactors = FALSE), caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: Imputed data: summary(chain:5)'),
extensions = 'Buttons', options = list(dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print')))
# 8.a. To cast the imputed numbers as integers (not necessary, but may be useful)
<- sapply(data.frames1[[5]], is.numeric) # get the indices of numeric columns
indx 5]][indx] <- lapply(data.frames1[[5]][indx], function(x) as.numeric(as.integer(x))) # cast each value as integer
data.frames1[[# data.frames[[5]]$spikes.hr
# 9. Save results out
write.csv(data.frames1[[5]], "C:\\Users\\Dinov\\Desktop\\TBI_MIData.csv")
# 10. Complete Data analytics functions:
# library("mi")
#lm.mi(); glm.mi(); polr.mi(); bayesglm.mi(); bayespolr.mi(); lmer.mi(); glmer.mi()
# 10.1 Define Linear Regression for multiply imputed dataset - Also see Step (12)
##linear regression for each imputed data set - 5 regression models are fit
<- glm(ever.sz ~ surgery + worst.gcs + factor(sex) + age, data.frames1$`chain:1`, family = "binomial"); summary(fit_lm1); display(fit_lm1) fit_lm1
##
## Call:
## glm(formula = ever.sz ~ surgery + worst.gcs + factor(sex) + age,
## family = "binomial", data = data.frames1$`chain:1`)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.7446 -1.1443 0.8003 1.0161 1.4430
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.550959 1.412321 0.390 0.696
## surgery1 1.096921 0.712894 1.539 0.124
## worst.gcs -0.113219 0.104958 -1.079 0.281
## factor(sex)Male -0.389622 0.851250 -0.458 0.647
## age 0.001414 0.019692 0.072 0.943
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 62.371 on 45 degrees of freedom
## Residual deviance: 59.353 on 41 degrees of freedom
## AIC: 69.353
##
## Number of Fisher Scoring iterations: 4
## glm(formula = ever.sz ~ surgery + worst.gcs + factor(sex) + age,
## family = "binomial", data = data.frames1$`chain:1`)
## coef.est coef.se
## (Intercept) 0.55 1.41
## surgery1 1.10 0.71
## worst.gcs -0.11 0.10
## factor(sex)Male -0.39 0.85
## age 0.00 0.02
## ---
## n = 46, k = 5
## residual deviance = 59.4, null deviance = 62.4 (difference = 3.0)
# Fit the appropriate model and pool the results (estimates over MI chains)
<- pool(ever.sz ~ surgery + worst.gcs + factor(sex) + age, family = "binomial", data=imputations1, m=5)
model_results display (model_results); summary (model_results)
## bayesglm(formula = ever.sz ~ surgery + worst.gcs + factor(sex) +
## age, data = imputations1, m = 5, family = "binomial")
## coef.est coef.se
## (Intercept) 0.25 1.25
## surgery1 0.83 0.64
## worst.gcs -0.06 0.09
## factor(sex)Male -0.29 0.76
## age 0.00 0.02
## n = 41, k = 5
## residual deviance = 60.0, null deviance = 62.4 (difference = 2.3)
##
## Call:
## pool(formula = ever.sz ~ surgery + worst.gcs + factor(sex) +
## age, data = imputations1, m = 5, family = "binomial")
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.6500 -1.2286 0.8518 1.0091 1.3405
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.246116 1.245631 0.198 0.843
## surgery1 0.830523 0.640016 1.298 0.194
## worst.gcs -0.056993 0.093729 -0.608 0.543
## factor(sex)Male -0.291128 0.758463 -0.384 0.701
## age 0.003799 0.018021 0.211 0.833
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 62.371 on 45 degrees of freedom
## Residual deviance: 60.032 on 41 degrees of freedom
## AIC: 70.032
##
## Number of Fisher Scoring iterations: 6.2
# Report the summaries of the imputations
<- complete(imputations1, 3) # extract the first 3 chains
data.frames <-lapply(data.frames1, summary)
mySummary2
datatable(data.frame(t(as.matrix(unclass(mySummary2$`chain:1`))), check.names = FALSE, stringsAsFactors = FALSE), caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: Imputed data: summary(chain:1)'))
# 11. Validation: we now verify whether enough iterations were conducted.
# Validation criteria demands that the mean of each completed variable should
# be similar for each of the k chains (in this case k=5).
# mipply is wrapper for sapply invoked on mi-class objects to compute the col means
round(mipply(imputations1, mean, to.matrix = TRUE), 3)
## chain:1 chain:2 chain:3 chain:4 chain:5
## id 23.500 23.500 23.500 23.500 23.500
## age 0.000 0.000 0.000 0.000 0.000
## sex 1.804 1.804 1.804 1.804 1.804
## mechanism 4.261 4.261 4.261 4.261 4.261
## field.gcs 0.054 0.035 -0.041 0.053 -0.028
## er.gcs 0.016 -0.059 -0.017 -0.055 -0.057
## icu.gcs -0.015 0.006 -0.015 -0.005 -0.021
## worst.gcs -0.008 0.027 0.013 0.013 0.024
## X6m.gose 0.075 0.038 0.059 0.040 -0.009
## X2013.gose 0.000 0.000 0.000 0.000 0.000
## skull.fx 1.609 1.609 1.609 1.609 1.609
## temp.injury 1.587 1.587 1.587 1.587 1.587
## surgery 1.630 1.630 1.630 1.630 1.630
## spikes.hr 43.833 48.948 94.391 39.531 77.218
## min.hr -0.090 -0.239 -0.151 -0.080 0.048
## max.hr -0.044 -0.115 0.069 -0.062 0.049
## acute.sz 1.174 1.174 1.174 1.174 1.174
## late.sz 1.565 1.565 1.565 1.565 1.565
## ever.sz 1.587 1.587 1.587 1.587 1.587
## missing_field.gcs 0.043 0.043 0.043 0.043 0.043
## missing_er.gcs 0.043 0.043 0.043 0.043 0.043
## missing_icu.gcs 0.022 0.022 0.022 0.022 0.022
## missing_worst.gcs 0.022 0.022 0.022 0.022 0.022
## missing_X6m.gose 0.109 0.109 0.109 0.109 0.109
## missing_spikes.hr 0.391 0.391 0.391 0.391 0.391
## missing_min.hr 0.391 0.391 0.391 0.391 0.391
## missing_max.hr 0.391 0.391 0.391 0.391 0.391
# Rhat convergence statistics compares the variance between chains to the variance
# within chains (similar to the ANOVA F-test).
# Rhat Values ~ 1.0 indicate likely convergence,
# Rhat Values > 1.1 indicate that the chains should be run longer
# (use large number of iterations)
Rhats(imputations1, statistic = "moments") # assess the convergence of MI algorithm
## mean_field.gcs mean_er.gcs mean_icu.gcs mean_worst.gcs mean_X6m.gose
## 1.877840 2.355414 2.113877 2.420849 1.324775
## mean_spikes.hr mean_min.hr mean_max.hr sd_field.gcs sd_er.gcs
## 2.976167 1.830635 2.024809 1.480897 1.414323
## sd_icu.gcs sd_worst.gcs sd_X6m.gose sd_spikes.hr sd_min.hr
## 1.255869 1.371200 1.255485 2.474809 1.192194
## sd_max.hr
## 1.210353
# When convergence is unstable, we can continue the iterations for all chains, e.g.
<- mi(imputations1, n.iter=20) # add additional 20 iterations
imputations1
# To plot the produced mi results, for all missing_variables we can generate
# a histogram of the observed, imputed, and completed data.
# We can compare of the completed data to the fitted values implied by the model
# for the completed data, by plotting binned residuals.
# hist function works similarly as plot.
# image function gives a sense of the missingness patterns in the data
plot(imputations1); hist(imputations1); image(imputations1)
<-lapply(data.frames1, summary)
mySummary3
datatable(data.frame(t(as.matrix(unclass(mySummary3$`chain:1`))), check.names = FALSE, stringsAsFactors = FALSE), caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: Imputed data: summary(chain:1)'))
# 12. Finally, pool over the m = 5 imputed datasets when we fit the "model"
# Pool from across the 4 chains - in order to estimate a linear regression model
# and impact of various predictors
<- pool(ever.sz ~ surgery + worst.gcs + factor(sex) + age, data = imputations1, m = 5 ); display (model_results); summary (model_results) model_results
## bayesglm(formula = ever.sz ~ surgery + worst.gcs + factor(sex) +
## age, data = imputations1, m = 5)
## coef.est coef.se
## (Intercept) 0.17 1.23
## surgery1 0.79 0.63
## worst.gcs -0.04 0.09
## factor(sex)Male -0.29 0.76
## age 0.00 0.02
## n = 41, k = 5
## residual deviance = 60.2, null deviance = 62.4 (difference = 2.2)
##
## Call:
## pool(formula = ever.sz ~ surgery + worst.gcs + factor(sex) +
## age, data = imputations1, m = 5)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.6350 -1.2138 0.8681 1.0038 1.3220
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) 0.170121 1.232311 0.138 0.890
## surgery1 0.792642 0.633684 1.251 0.211
## worst.gcs -0.041583 0.092036 -0.452 0.651
## factor(sex)Male -0.286825 0.757743 -0.379 0.705
## age 0.004131 0.017999 0.230 0.818
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 62.371 on 45 degrees of freedom
## Residual deviance: 60.200 on 41 degrees of freedom
## AIC: 70.2
##
## Number of Fisher Scoring iterations: 6
coef(summary(model_results))[, 1:2] # get the model coef's and their SE's
## Estimate Std. Error
## (Intercept) 0.17012081 1.23231141
## surgery1 0.79264163 0.63368418
## worst.gcs -0.04158342 0.09203603
## factor(sex)Male -0.28682513 0.75774275
## age 0.00413088 0.01799940
Below we present the theory and practice of one specific statistical computing strategy for imputing incomplete datasets.
MCAR: Data which is Missing Completely At Random has nothing systematic about which observations are missing. There is no relationship between missingness and either observed or unobserved covariates.
MAR: Missing At Random is weaker than MCAR. The missingness is still random, but solely due to the observed variables. For example, those from a lower socioeconomic status (SES) may be less willing to provide salary information (but we know their SES). The key is that the missingness is not due to the values which are not observed. MCAR implies MAR, but not vice-versa.
MNAR: If the data are Missing Not At Random, then the missingness depends on the values of the missing data. Examples include censored data, self-reported data for individuals who are heavier, who are less likely to report their weight, and response-measuring device that can only measure values above \(0.5\), anything below that is missing.
Expectation-Maximization (EM) is an iterative process involving two steps - expectation and maximization, which are applied in tandem. EM can be employed to find parameter estimates using maximum likelihood and is specifically useful when the equations determining the relations of the data-parameters cannot be directly solved. For example, a Gaussian mixture modeling assumes that each data point (\(X\)) has a corresponding latent (unobserved) variable or a missing value (\(Y\)), which may be specified as a mixture of coefficients determining the affinity of the data as a linear combination of Gaussian kernels, determined by a set of parameters (\(\theta\)), e.g., means and variance-covariances. Thus, EM estimation relies on:
\[L(\theta | X) = p(X |\theta) =\int { p(X, Y |\theta)dY}.\]
Most of the time, this equation may not be directly solved, e.g., when \(Y\) is missing.
\[Q ( \theta | \theta^{(t)} ) = E_{Y | X, \theta^{(t)} }[ log \left ( L(\theta | X , Y ) \right ];\]
This SOCR EM Activity shows the practical aspects of applying the EM algorithm. Also, in DSPA Chapter 3 we will illustrate the EM method for fitting single distribution models or (linear) mixtures of distributions to data that may represent a blend of heterogeneous observations from multiple different processes.
The EM algorithm is an alternative to Newton-Raphson or the method of scoring for computing MLE in cases where there are complications in calculating the MLE. It is applicable for imputing incomplete MAR data, where the missing data mechanism can be ignored and separate parameters may be estimated for each missing feature.
Complete Data: \[ Z = \left(\begin{array}{cc} X \\ Y \end{array}\right), ZZ^T = \left(\begin{array}{cc} XX^T & XY^T \\ YX^T & YY^T \end{array}\right), \]
where \(X\) is the observed data and \(Y\) is the missing data.
Details: If \(o=obs\) and \(m=mis\) stand for observed and missing, the mean vector, \((\mu_{obs}, \mu_{mis})^T\), and the variance-covariance matrix, \(\Sigma^{(t)} = \left(\begin{array}{cc} \Sigma_{oo} & \Sigma_{om} \\ \Sigma_{mo} & \Sigma_{mm} \end{array}\right)\), are represented by:
\[ \mu^{(t)} = \left(\begin{array}{cc} \mu_{obs} \\ \mu_{mis} \end{array}\right),\;\;\;\;\; \Sigma^{(t)} = \left(\begin{array}{cc} \Sigma_{oo} & \Sigma_{om} \\ \Sigma_{mo} & \Sigma_{mm} \end{array}\right) \] E-step: \[ E(Z | X) = \left(\begin{array}{cc} X \\ E(Y|X) \end{array}\right),\;\;\;\;\; E(ZZ^T|X) = \left(\begin{array}{cc} XX^T & XE(Y|X)^T \\ E(Y|X)X^T & E(YY^T|X) \end{array}\right). \]
\[E(Y | X) = \mu_{mis} + \Sigma_{mo}\Sigma_{oo}^{-1}(X - \mu_{obs}).\] \[E(YY^T|X) = (\Sigma_{mm}-\Sigma_{mo}\Sigma_{oo}^{-1}\Sigma_{om})+E(Y|X)E(Y|X)^T.\]
M-step: \[\mu^{(t+1)} = \frac{1}{n}\sum_{i=1}^nE(Z|X).\] \[\Sigma^{(t+1)} = \frac{1}{n}\sum_{i=1}^nE(ZZ^T|X) - \mu^{(t+1)}{\mu^{(t+1)}}^T.\]
# simulate 20 (feature) vectors of 200 (cases) Normal Distributed random values (\mu, \Sigma)
# You can choose multiple distribution for testing
# sim_data <- replicate(20, rpois(50, 10))
set.seed(202227)
<- as.matrix(rep(2,20) )
mu <- diag(c(1:20) )
sig # Add a noise item. The noise is $ \epsilon ~ MVN(as.matrix(rep(0,20)), diag(rep(1,20)))$
<- mvrnorm(n = 200, mu, sig) +
sim_data mvrnorm(n=200, as.matrix(rep(0,20)), diag( rep(1,20) ))
# save these in the "original" object
<- sim_data
sim_data.orig
# install.packages("e1071")
# introduce 500 random missing indices (in the total of 4000=200*20)
# discrete distribution where the probability of the elements of values is proportional to probs,
# which are normalized to add up to 1.
<- e1071::rdiscrete(500, probs = rep(1,length(sim_data)), values = seq(1, length(sim_data)))
rand.miss <- NA
sim_data[rand.miss] sum(is.na(sim_data)) # check now many missing (NA) are there < 500
## [1] 466
# cast the data into a data.frame object and report 15*10 elements
<- data.frame(sim_data)
sim_data.df # kable( sim_data.df[1:15, 1:10], caption = "The first 15 rows and first 10 columns of the simulation data")
datatable(sim_data.df, caption = htmltools::tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table: Simulated Data (sim_data.df)'),
extensions = 'Buttons', options = list(dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print')))
# Define the EM imputation method
<- function(x, tol = 0.001) {
EM_algorithm # identify the missing data entries (Boolean indices)
<- is.na(x)
missvals # instantiate the EM-iteration
<- x
new.impute <- x
old.impute <- 1
count.iter <- 0
reach.tol
# compute \Sigma on complete data
<- as.matrix(var(na.exclude(x)))
sigma # compute the vector of feature (column) means
<- as.matrix(apply(na.exclude(x), 2, mean))
mean.vec
while (reach.tol != 1) {
for (i in 1:nrow(x)) {
<- (c(missvals[i, ]))
pick.miss if (sum(pick.miss) != 0) {
# compute inverse-Sigma_completeData, variance-covariance matrix
<- solve(sigma[!pick.miss, !pick.miss], tol = 1e-40)
inv.S
# Expectation Step
# $$E(Y|X)=\mu_{mis}+\Sigma_{mo}\Sigma_{oo}^{-1}(X-\mu_{obs})$$
<- mean.vec[pick.miss] +
new.impute[i, pick.miss] !pick.miss] %*% inv.S %*%
sigma[pick.miss,t(new.impute[i, !pick.miss]) - t(t(mean.vec[!pick.miss])))
(
}
}
# Maximization Step
# Recompute the complete \Sigma the complete vector of feature (column) means
#$$\Sigma^{(t+1)} = \frac{1}{n}\sum_{i=1}^nE(ZZ^T|X) - \mu^{(t+1)}{\mu^{(t+1)}}^T$$
<- var((new.impute))
sigma #$$\mu^{(t+1)} = \frac{1}{n}\sum_{i=1}^nE(Z|X)$$
<- as.matrix(apply(new.impute, 2, mean))
mean.vec
# Inspect for convergence tolerance, start with the 2nd iteration
if (count.iter > 1) {
for (l in 1:nrow(new.impute)) {
for (m in 1:ncol(new.impute)) {
if (abs((old.impute[l, m] - new.impute[l, m])) > tol) {
<- 0
reach.tol else {
} <- 1
reach.tol
}
}
}
}<- count.iter + 1
count.iter <- new.impute
old.impute
}
# return the imputation output of the current iteration that passed the tolerance level
return(new.impute)
}
<- EM_algorithm(sim_data.df, tol=0.0001) sim_data.imputed
Smaller black colored points represent observed data, and magenta-color and circle-shapes denote the imputed data.
<- function(index1, index2){
plot.me <- sim_data.imputed[row.names(
plot.imputed subset(sim_data.df, is.na(sim_data.df[, index1]) | is.na(sim_data.df[, index2]))), ]
= ggplot(sim_data.imputed, aes_string( paste0("X",index1) , paste0("X",index2 ))) +
p geom_point(alpha = 0.5, size = 0.7)+theme_bw() +
stat_ellipse(type = "norm", color = "#000099", alpha=0.5) +
geom_point(data = plot.imputed, aes_string( paste0("X",index1) , paste0("X",(index2))),size = 1.5, color = "Magenta", alpha = 0.8)
}
::grid.arrange( plot.me(1,2), plot.me(5,6), plot.me(13,20), plot.me(18,19), nrow = 2) gridExtra
=1; index2=5
index1<- sim_data.imputed[row.names(
plot.imputed subset(sim_data.df, is.na(sim_data.df[, index1]) | is.na(sim_data.df[, index2]))), ]
= ggplot(sim_data.imputed, aes_string( paste0("X",index1) , paste0("X",index2 ))) +
p geom_point(alpha = 0.5, size = 0.7)+theme_bw() +
stat_ellipse(type = "norm", color = "#000099", alpha=0.5) +
geom_point(data = plot.imputed, aes_string( paste0("X",index1) , paste0("X",(index2))),size = 1.5, color = "Magenta", alpha = 0.8)
plot_ly(sim_data.imputed, x = ~X1, y = ~X5, type = "scatter",
mode = "markers") %>%
layout(title='Scatterplot: Improved Water Quality vs. Sanitation Facilities',
xaxis = list (title = 'Water Quality'), yaxis = list (title = 'Sanitation'))
Amelia
R PackageLet’s use the amelia
function to impute the original data sim_data_df and compare the results to the simpler manual EM_algorithm
imputation defined above.
# install.packages("Amelia")
library(Amelia)
## Loading required package: Rcpp
## ##
## ## Amelia II: Multiple Imputation
## ## (Version 1.8.0, built: 2021-05-26)
## ## Copyright (C) 2005-2021 James Honaker, Gary King and Matthew Blackwell
## ## Refer to http://gking.harvard.edu/amelia/ for more information
## ##
dim(sim_data.df)
## [1] 200 20
<- amelia(sim_data.df, m = 5) amelia.out
## -- Imputation 1 --
##
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
## 21
##
## -- Imputation 2 --
##
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
##
## -- Imputation 3 --
##
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
##
## -- Imputation 4 --
##
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
##
## -- Imputation 5 --
##
## 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
## 21 22 23
amelia.out
##
## Amelia output with 5 imputed datasets.
## Return code: 1
## Message: Normal EM convergence.
##
## Chain Lengths:
## --------------
## Imputation 1: 21
## Imputation 2: 17
## Imputation 3: 17
## Imputation 4: 15
## Imputation 5: 23
.5 <- amelia.out$imputations[[5]] amelia.imputed
EM_algorithm
<- function(index, index2){
plot.ii2 <- sim_data.imputed[row.names(
plot.imputed subset(sim_data.df, is.na(sim_data.df[, index]) | is.na(sim_data.df[, index2]))), ]
<- amelia.imputed.5[row.names(
plot.imputed2 subset(sim_data.df, is.na(sim_data.df[, index]) | is.na(sim_data.df[, index2]))), ]
= ggplot(sim_data.imputed, aes_string( paste0("X",index) , paste0("X",index2 ))) +
p geom_point(alpha = 0.8, size = 0.7)+theme_bw() +
stat_ellipse(type = "norm", color = "#000099", alpha=0.5) +
geom_point(data = plot.imputed, aes_string( paste0("X",index) , paste0("X",(index2))),size = 2.5, color = "Magenta", alpha = 0.9, shape = 16) +
geom_point(data = plot.imputed2, aes( X1 , X2),size = 2.5, color = "#FF9933", alpha = 0.8, shape = 18)
return(p)
}
plot.ii2(2, 4)
plot.ii2(17, 18)
Finally, we can compare the densities of the original, manually-imputed and Amelia-imputed datasets. Remember that in this simulation, we had about \(500\) observations missing out of the \(4,000\) that we synthetically generated.
##
## Attaching package: 'tidyr'
## The following object is masked from 'package:mi':
##
## complete
## The following objects are masked from 'package:Matrix':
##
## expand, pack, unpack
In this section, we will utilize the Earthquakes dataset on SOCR website. It records information about earthquakes happened between 1969 and 2007 with magnitudes larger than 5 on the Richter scale. Here is how we parse the data on the source webpage and ingest the information into R:
# install.packages("xml2")
library("XML"); library("xml2")
## Warning: package 'XML' was built under R version 4.1.1
library("rvest")
<- read_html("https://wiki.socr.umich.edu/index.php/SOCR_Data_Dinov_021708_Earthquakes")
wiki_url html_nodes(wiki_url, "#content")
## {xml_nodeset (1)}
## [1] <div id="content" class="mw-body" role="main">\n\t\t\t<a id="top"></a>\n\ ...
<- html_table(html_nodes(wiki_url, "table")[[2]]) earthquake
In this dataset, Magt
(magnitude type) may be used as grouping variable. We will draw a “Longitude vs Latitude” line plot from this dataset. The function we are using is called ggplot()
under ggplot2
. The input type for this function is mostly data frame. aes()
specifies axes.
# library(ggplot2)
# plot4<-ggplot(earthquake, aes(Longitude, Latitude, group=Magt, color=Magt))+
# geom_point(data=earthquake, size=4, mapping=aes(x=Longitude, y=Latitude, shape=Magt))
# plot4 # or plint(plot4)
# https://plotly-r.com/working-with-symbols.html
<- function (name) {
glyphication = vector()
glyphfor (i in 1:length(name)){
="triangle-up"
glyph[i]if (name[i]=="Md") { glyph[i]="diamond-open" }
else if (name[i]=="ML") { glyph[i]="circle-open" }
else if (name[i]=="Mw") { glyph[i]="square-open" }
else if (name[i]=="Mx") { glyph[i]="x-open" }
}return(glyph)
}$glyph <- glyphication(earthquake$Magt)
earthquake
plot_ly(earthquake) %>%
add_markers(x = ~Longitude, y = ~Latitude, type = "scatter", color = ~Magt,
mode = "markers", marker = list(size = ~Depth, color = ~Magt, symbol = ~glyph,
line = list(color = "black",width = 2))) %>%
layout(title="California Earthquakes (1969 - 2007)")
We can see the most important line of code was made up with 2 parts. The first part ggplot(earthquake, aes(Longiture, Latitude, group=Magt, color=Magt))
specifies the setting of the plot: dataset, group and color. The second part specifies we are going to draw lines between data points. In later chapters we will frequently use package ggplot2
and the structure under this great package is always function1+function2
.
We can visualize the distribution for different variables using density plots. The following chunk of codes plots the distribution for Latitude among different Magnitude types. Also, it is using ggplot()
function but combined with geom_density()
.
<-ggplot(earthquake, aes(Latitude, size=1))+geom_density(aes(color=Magt))
plot5 plot5
## Warning: Groups with fewer than two data points have been dropped.
## Warning in max(ids, na.rm = TRUE): no non-missing arguments to max; returning
## -Inf
We can also compute and display 2D Kernel Density and 3D Surface Plots. Plotting 2D Kernel Density and 3D Surface plots is very important and useful in multivariate exploratory data analytic.
We will use plot_ly()
function under plotly
package, which takes value from a data frame.
To create a surface plot, we use two vectors: x and y with length m and n respectively. We also need a matrix: z of size \(m\times n\). This z matrix is created from matrix multiplication between x and y.
The kde2d()
function is needed for 2D kernel density estimation.
<- with(earthquake, MASS::kde2d(Longitude, Latitude, n = 50)) kernal_density
Here z
is an estimate of the kernel density function. Then we apply plot_ly
to the list kernal_density
via with()
function.
library(plotly)
with(kernal_density, plot_ly(x=x, y=y, z=z, type="surface"))
Note that we used the option "surface"
, however you can experiment with the type
option.
Alternatively, one can plot 1D, 2D or 3D plots:
plot_ly(x = ~ earthquake$Longitude)
## No trace type specified:
## Based on info supplied, a 'histogram' trace seems appropriate.
## Read more about this trace type -> https://plotly.com/r/reference/#histogram
plot_ly(x = ~ earthquake$Longitude, y = ~earthquake$Latitude)
## No trace type specified:
## Based on info supplied, a 'scatter' trace seems appropriate.
## Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No scatter mode specifed:
## Setting the mode to markers
## Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
plot_ly(x = ~ earthquake$Longitude, y = ~earthquake$Latitude, z=~earthquake$Mag)
## No trace type specified:
## Based on info supplied, a 'scatter3d' trace seems appropriate.
## Read more about this trace type -> https://plotly.com/r/reference/#scatter3d
## No scatter3d mode specifed:
## Setting the mode to markers
## Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
<- data.frame(x=earthquake$Longitude, y=earthquake$Latitude, z=earthquake$Mag)
df3D
# Convert he Long (X, Y, Z) Earthquake format data into a Matrix Format
# install.packages("Matrix")
library("Matrix")
<- with(df3D, sparseMatrix(i = as.numeric(180-x), j=as.numeric(y), x=z, use.last.ij=T, dimnames=list(levels(x), levels(y))))
matrix_EarthQuakes dim(matrix_EarthQuakes)
## [1] 307 44
# colnames(matrix_EarthQuakes) <- seq(from=earthquake$Longitude[1],
# to=earthquake$Longitude[length(earthquake$Longitude)],
# length.out=dim(matrix_EarthQuakes)[2])
# rownames(matrix_EarthQuakes) <- seq(from=earthquake$Latitude[1],
# to=earthquake$Latitude[length(earthquake$Latitude)],
# length.out=dim(matrix_EarthQuakes)[1])
# View(as.matrix(matrix_EarthQuakes))
# view matrix is 2D heatmap:
library("ggplot2"); library("gplots")
## Registered S3 method overwritten by 'gplots':
## method from
## reorder.factor gdata
##
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
##
## lowess
# heatmap.2( as.matrix(matrix_EarthQuakes[280:307, 30:44]), Rowv=FALSE, Colv=FALSE, dendrogram='none', cellnote=as.matrix(matrix_EarthQuakes[280:307, 30:44]), notecol="black", trace='none', key=FALSE, lwid = c(.01, .99), lhei = c(.01, .99), margins = c(5, 15 ))
plot_ly(z = ~as.matrix(matrix_EarthQuakes[280:307, 30:44]), type = "heatmap") %>% hide_colorbar()
# plot_ly(x=~colnames(matrix_EarthQuakes[280:307, 30:44]),
# y=~rownames(matrix_EarthQuakes[280:307, 30:44]),
# z = ~as.matrix(matrix_EarthQuakes[280:307, 30:44]), type = "heatmap") %>%
# layout(title="California Earthquakes Heatmap",
# xaxis=list(title="Longitude"), yaxis=list(title="Latitude")) %>%
# hide_colorbar()
# Long -180<x<-170, Lat: 30<y<45, Z: 5<Mag<8
<- with(df3D, sparseMatrix(i = as.numeric(180+x), j=as.numeric(y), x=z, use.last.ij=TRUE, dimnames=list(levels(x), levels(y))))
matrix_EarthQuakes <- as.matrix(matrix_EarthQuakes)
mat1 plot_ly(z = ~mat1, type = "surface")
# To plot the Aggregate (Summed) Magnitudes at all Long/Lat:
<- with(df3D, sparseMatrix(i = as.numeric(180+x), j=as.numeric(y), x=z, dimnames=list(levels(x), levels(y))))
matrix_EarthQuakes <- as.matrix(matrix_EarthQuakes)
mat1 plot_ly(z = ~mat1, type = "surface")
# plot_ly(z = ~mat1[30:60, 20:40], type = "surface")
Comparing cohorts with imbalanced sample sizes (unbalanced designs) may present hidden biases in the results. Frequently, a cohort-rebalancing protocol is necessary to avoid such unexpected effects. Extremely unequal sample sizes can invalidate various parametric assumptions (e.g., homogeneity of variances). Also, there may be insufficient data representing the patterns belonging to the minority class(es) leading to inadequate capturing of the feature distributions. Although, the groups do not have to have equal sizes, a general rule of thumb is that group sizes where one groups is more than an order of magnitude larger than the size of another group has the potential
for bias.
Example 1: Parkinson’s Diseases Study involving neuroimaging, genetics, clinical, and phenotypic data for over 600 volunteers produced multivariate data for 3 cohorts – HC=Healthy Controls(166) , PD=Parkinson’s (434), SWEDD= subjects without evidence for dopaminergic deficit (61).
# update packages
# update.packages()
# load the data: 06_PPMI_ClassificationValidationData_Short.csv
<-read.csv("https://umich.instructure.com/files/330400/download?download_frd=1", header=TRUE)
ppmi_data
table(ppmi_data$ResearchGroup)
# binarize the Dx classes
$ResearchGroup <- ifelse(ppmi_data$ResearchGroup == "Control", "Control", "Patient")
ppmi_dataattach(ppmi_data)
head(ppmi_data)
# Model-free analysis, classification
# install.packages("crossval")
# install.packages("ada")
# library("crossval")
require(crossval)
require(ada)
#set up adaboosting prediction function
# Define a new classification result-reporting function
<- function (train.x, train.y, test.x, test.y, negative, formula){
my.ada <- ada(train.x, train.y)
ada.fit <- predict(ada.fit, test.x)
predict.y #count TP, FP, TN, FN, Accuracy, etc.
<- confusionMatrix(test.y, predict.y, negative = negative)
out # negative is the label of a negative "null" sample (default: "control").
return (out)
}
# balance cases
# SMOTE: Synthetic Minority Oversampling Technique to handle class imbalance in binary classification.
set.seed(1000)
# install.packages("unbalanced") to deal with unbalanced group data
require(unbalanced)
$PD <- ifelse(ppmi_data$ResearchGroup=="Control", 1, 0)
ppmi_data<- unique(ppmi_data$FID_IID)
uniqueID <- ppmi_data[ppmi_data$VisitID==1, ]
ppmi_data $PD <- factor(ppmi_data$PD)
ppmi_data
colnames(ppmi_data)
# ppmi_data.1<-ppmi_data[, c(3:281, 284, 287, 336:340, 341)]
<- ncol(ppmi_data)
n .1 <- ppmi_data$PD
output
# remove Default Real Clinical subject classifications!
$PD <- ifelse(ppmi_data$ResearchGroup=="Control", 1, 0)
ppmi_data<- ppmi_data[ , -which(names(ppmi_data) %in% c("ResearchGroup", "PD", "X", "FID_IID"))]
input # output <- as.matrix(ppmi_data[ , which(names(ppmi_data) %in% {"PD"})])
<- as.factor(ppmi_data$PD)
output c(dim(input), length(output))
#balance the dataset
.1<-ubBalance(X= input, Y=output, type="ubSMOTE", percOver=300, percUnder=150, verbose=TRUE)
data# percOver = A number that drives the decision of how many extra cases from the minority class are generated (known as over-sampling).
# k = A number indicating the number of nearest neighbors that are used to generate the new examples of the minority class.
# percUnder = A number that drives the decision of how many extra cases from the majority classes are selected for each case generated from the minority class (known as under-sampling)
<-cbind(data.1$X, data.1$Y)
balancedDatatable(data.1$Y)
nrow(data.1$X); ncol(data.1$X)
nrow(balancedData); ncol(balancedData)
nrow(input); ncol(input)
colnames(balancedData) <- c(colnames(input), "PD")
# check visually for differences between the distributions of the raw (input) and rebalanced data (for only one variable, in this case)
<- qqplot(input[, 5], balancedData [, 5], plot.it=F)
QQ
plot_ly(x=~QQ$x, y = ~QQ$y, type="scatter", mode="markers", showlegend=F) %>%
add_lines(x=c(0,0.8), y=c(0,0.8), showlegend=F) %>%
layout(title="QQ-Plot Original vs. Rebalanced Data", xaxis=list(title="original data"),
yaxis=list(title="Rebalanced data"))
###Check balance
## Wilcoxon test
0.05 <- 0.05
alpha.<- NULL # binarized/dichotomized p-values
test.results.bin <- NULL # raw p-values
test.results.raw
for (i in 1:(ncol(balancedData)-1))
{<- wilcox.test(input[, i], balancedData [, i])$p.value
test.results.raw [i] <- ifelse(test.results.raw [i] > alpha.0.05, 1, 0)
test.results.bin [i] print(c("i=", i, "Wilcoxon-test=", test.results.raw [i]))
}print(c("Wilcoxon test results: ", test.results.bin))
<- stats::p.adjust(test.results.raw, method = "fdr", n = length(test.results.raw))
test.results.corr # where methods are "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none")
# plot(test.results.raw, test.results.corr)
# zeros (0) are significant independent between-group T-test differences, ones (1) are insignificant
plot_ly(x=~test.results.raw, y = ~test.results.corr, type="scatter", mode="markers", showlegend=F) %>%
add_lines(x=c(0,1), y=c(0,1), showlegend=F) %>%
layout(title="Wilcoxon test results - Original vs. Rebalanced Data", xaxis=list(title="Original"),
yaxis=list(title="Rebalanced"))
# Check the Differences between the rate of significance between the raw and FDR-corrected p-values
<- ifelse(test.results.raw > alpha.0.05, 1, 0)
test.results.bin table(test.results.bin)
<- ifelse(test.results.corr > alpha.0.05, 1, 0)
test.results.corr.bin table(test.results.corr.bin)
Notes
percOver
parameter (perc.over/100) represents the number of new instances generated for each rare instance in the minority sample, when \(perc.over < 100\), a single instance is generated. For example, percOver=300
and percOver=30
would triple (300/100) and leave unchanged (30/100) the size of the minority sample, respectively.percUnder
(perc.under/100) represents the number of “normal” (majority class) instances that are randomly selected for each smoted (synthetically generated) observation. For instance, percUnder=300
or percUnder=30
would downsample the majority sample by choosing one-out-of-each-three or all of the majority sample points, respectively.We can also import SQL databases in to R. First, we need to install and load the RODBC(R Open Database Connectivity) package.
# install.packages("RODBC", repos = "http://cran.us.r-project.org")
library(RODBC)
Then, we could open a connection to the SQL server database with Data Source Name (DSN), via Microsoft Access. More details are provided here and here.
#Right Skewed
<- 10000
N <- rnbinom(N, 10, .5)
x hist(x,
xlim=c(min(x), max(x)), probability=T, nclass=max(x)-min(x)+1,
col='lightblue', xlab=' ', ylab=' ', axes=F,
main='Right Skewed')
lines(density(x, bw=1), col='red', lwd=3)
#No Skew
<- 10000
N <- rnorm(N, 0, 1)
x hist(x, probability=T,
col='lightblue', xlab=' ', ylab=' ', axes=F,
main='No Skew')
lines(density(x, bw=0.4), col='red', lwd=3)
#Uniform density
<-runif(1000, 1, 50)
xhist(x, col='lightblue', main="Uniform Distribution", probability = T, xlab="", ylab="Density", axes=F)
abline(h=0.02, col='red', lwd=3)
#68-95-99.7 rule
<- rnorm(N, 0, 1)
x hist(x, probability=T,
col='lightblue', xlab=' ', ylab=' ', axes = F,
main='68-95-99.7 Rule')
lines(density(x, bw=0.4), col='red', lwd=3)
axis(1, at=c(-3, -2, -1, 0, 1, 2, 3), labels = expression(mu-3*sigma, mu-2*sigma, mu-sigma, mu, mu+sigma, mu+2*sigma, mu+3*sigma))
abline(v=-1, lwd=3, lty=2)
abline(v=1, lwd=3, lty=2)
abline(v=-2, lwd=3, lty=2)
abline(v=2, lwd=3, lty=2)
abline(v=-3, lwd=3, lty=2)
abline(v=3, lwd=3, lty=2)
text(0, 0.2, "68%")
segments(-1, 0.2, -0.3, 0.2, col = 'red', lwd=2)
segments(1, 0.2, 0.3, 0.2, col = 'red', lwd=2)
text(0, 0.15, "95%")
segments(-2, 0.15, -0.3, 0.15, col = 'red', lwd=2)
segments(2, 0.15, 0.3, 0.15, col = 'red', lwd=2)
text(0, 0.1, "99.7%")
segments(-3, 0.1, -0.3, 0.1, col = 'red', lwd=2)
segments(3, 0.1, 0.3, 0.1, col = 'red', lwd=2)