From time to time I have wanted to bring an online table into an R dataframe. While in principle, the data can be cut and paste into Excel, sometimes the table is very large and sometimes the columns get goofed up in the process. Fortunately, there are a number of R tools for accomplishing this. I am just going to show one approach using the rvest package. The rvest package also makes it possible to interact with forms on webpages to request specific material which can then be scraped. I think you will see the potential if you look here.
In our (simple) case, we will apply this process to Westgard's desirable assay specifications as shown on his website. The goal is to parse out the biological variation tables, get them into a dataframe and the write to csv or xlsx.
The first thing to do is to load the rvest
and httr
packages and define an html session with the html_session()
function.
library(rvest) library(httr) wg <- html_session("https://www.westgard.com/biodatabase1.htm", user_agent("LabRtorian"))
Now looking at the webpage, you can see that there are 8 columns in the tables of interest. So, we will define an empty dataframe with 8 columns.
#define empty table to hold all the content biotable = data.frame(matrix(NA,0, 8))
We need to know which part of the document to scrape. This is a little obscure, but following the instructions in this post, we can determine that the xpaths we need are:
/html/body/div[1]/div[3]/div/main/article/div/table[1]
/html/body/div[1]/div[3]/div/main/article/div/table[2]
/html/body/div[1]/div[3]/div/main/article/div/table[3]
…
etc.
There are 8 such tables in the whole webpage. We can define a character vector for these as such:
xpaths <- paste0("/html/body/div[1]/div[3]/div/main/article/div/table[", 1:8, "]")
Now we make a loop to scrape the 8 tables and with each iteration of the loop, append the scraped subtable
to the main dataframe called biotable
using the rbind()
function. We have to use the parameter fill = TRUE
in the html_table()
function because the table does not happen to always a uniform number of columns.
for (j in 1:8){ subtable <- wg %>% read_html() %>% html_nodes(xpath = xpaths[j]) %>% html_table(., fill = TRUE) subtable <- subtable[[1]] biotable <- rbind(biotable,subtable) }
Now that we have the raw data out, we can have a quick look at it:
X1 | X2 | X3 | X4 | X5 | X6 | X7 | X8 |
---|---|---|---|---|---|---|---|
Analyte | Number of Papers | Biological Variation | Biological Variation | Desirable specification | Desirable specification | Desirable specification | |
Analyte | Number of Papers | CVI | CVg | I(%) | B(%) | TE(%) | |
S- | 11-Desoxycortisol | 2 | 21.3 | 31.5 | 10.7 | 9.5 | 27.1 |
S- | 17-Hydroxyprogesterone | 2 | 19.6 | 50.4 | 9.8 | 13.5 | 29.7 |
U- | 4-hydroxy-3-methoximandelate (VMA) | 1 | 22.2 | 47.0 | 11.1 | 13.0 | 31.3 |
S- | 5' Nucleotidase | 2 | 23.2 | 19.9 | 11.6 | 7.6 | 26.8 |
U- | 5'-Hydroxyindolacetate, concentration | 1 | 20.3 | 33.2 | 10.2 | 9.7 | 26.5 |
S- | α1-Acid Glycoprotein | 3 | 11.3 | 24.9 | 5.7 | 6.8 | 16.2 |
S- | α1-Antichymotrypsin | 1 | 13.5 | 18.3 | 6.8 | 5.7 | 16.8 |
S- | α1-Antitrypsin | 3 | 5.9 | 16.3 | 3.0 | 4.3 | 9.2 |
We can see that we need define column names and we need to get rid of some rows containing extraneous column header information. There are actually 8 such sets of headers to remove.
table.header <- c("Sample", "Analyte" ,"NumPapers", "CVI", "CVG", "I", "B","TE") names(biotable) <- table.header
Let's now find rows we don't want and remove them.
for.removal <- grep("Analyte", biotable$Analyte) biotable <- biotable[-for.removal,]
You will find that the table has missing data which is written as “- – -”. This should be now replaced by NA
and the column names should be assigned to sequential integers. Also, we will remove all the minus signs after the specimen type. I'm not sure what they add.
biotable[biotable == "---"] <- NA row.names(biotable) <- 1:nrow(biotable) biotable$Sample <- gsub("-", "", biotable$Sample, fixed = TRUE)
Just having another look at the first 10 rows:
Sample | Analyte | NumPapers | CVI | CVG | I | B | TE |
---|---|---|---|---|---|---|---|
S | 11-Desoxycortisol | 2 | 21.3 | 31.5 | 10.7 | 9.5 | 27.1 |
S | 17-Hydroxyprogesterone | 2 | 19.6 | 50.4 | 9.8 | 13.5 | 29.7 |
U | 4-hydroxy-3-methoximandelate (VMA) | 1 | 22.2 | 47.0 | 11.1 | 13.0 | 31.3 |
S | 5' Nucleotidase | 2 | 23.2 | 19.9 | 11.6 | 7.6 | 26.8 |
U | 5'-Hydroxyindolacetate, concentration | 1 | 20.3 | 33.2 | 10.2 | 9.7 | 26.5 |
S | α1-Acid Glycoprotein | 3 | 11.3 | 24.9 | 5.7 | 6.8 | 16.2 |
S | α1-Antichymotrypsin | 1 | 13.5 | 18.3 | 6.8 | 5.7 | 16.8 |
S | α1-Antitrypsin | 3 | 5.9 | 16.3 | 3.0 | 4.3 | 9.2 |
S | α1-Globulins | 2 | 11.4 | 22.6 | 5.7 | 6.3 | 15.7 |
U | α1-Microglobulin, concentration, first morning | 1 | 33.0 | 58.0 | 16.5 | 16.7 | 43.9 |
Now examining the structure:
str(biotable)
## 'data.frame': 370 obs. of 8 variables: ## $ Sample : chr "S" "S" "U" "S" ... ## $ Analyte : chr "11-Desoxycortisol" "17-Hydroxyprogesterone" "4-hydroxy-3-methoximandelate (VMA)" "5' Nucleotidase" ... ## $ NumPapers: chr "2" "2" "1" "2" ... ## $ CVI : chr "21.3" "19.6" "22.2" "23.2" ... ## $ CVG : chr "31.5" "50.4" "47.0" "19.9" ... ## $ I : chr "10.7" "9.8" "11.1" "11.6" ... ## $ B : chr "9.5" "13.5" "13.0" "7.6" ... ## $ TE : chr "27.1" "29.7" "31.3" "26.8" ...
It's kind-of undesirable to have numbers as characters so…
#convert appropriate columns to numeric biotable[,3:8] <- lapply(biotable[3:8], as.numeric)
Using the xlsx
package, you can output the table to an Excel file in the current working directory.
library(xlsx) write.xlsx(biotable, file = "Westgard_Biological_Variation.xlsx", row.names = FALSE)
If you are having trouble getting xlsx
to install, then just write as csv.
write.csv(biotable, file = "Westgard_Biological_Variation.csv", row.names = FALSE)
You can now use the same general approach to parse any table you have web access to, no mater how small or big it is. Here is a complete script in one place:
library(httr) library(rvest) library(xlsx) wg <- html_session("https://www.westgard.com/biodatabase1.htm", user_agent("yournamehere")) xpaths <- paste0("/html/body/div[1]/div[3]/div/main/article/div/table[", 1:8, "]") #define empty dataframe biotable = data.frame(matrix(NA,0, 8)) #loop over the 8 html tables for (j in 1:8){ subtable <- wg %>% read_html() %>% html_nodes(xpath = xpaths[j] ) %>% html_table(., fill = TRUE) subtable <- subtable[[1]] biotable <- rbind(biotable,subtable) } table.header <- c("Sample", "Analyte" ,"NumPapers", "CVI", "CVG", "I", "B","TE") names(biotable) <- table.header #remove extraneous rows for.removal <- grep("Analyte", biotable$Analyte) biotable <- biotable[-for.removal,] #make missing data into NA biotable[ biotable == "---" ] <- NA row.names(biotable) <- 1:nrow(biotable) #convert appropriate columns to numeric biotable[,3:8] <- lapply(biotable[3:8], as.numeric) #get rid of minus signs in column 1 biotable$Sample <- gsub("-", "", biotable$Sample, fixed = TRUE) write.xlsx(biotable, file = "Westgard_Biological_Variation.xlsx", row.names = FALSE) write.csv(biotable, file = "Westgard_Biological_Variation.csv", row.names = FALSE)
Parting Thought on Tables
You prepare a table before me in the presence of my enemies. You anoint my head with oil; my cup overflows.
(Psalm 23:5)
]]>At the AACC meeting last week, some of my friends were bugging me that I had not made a blog post in 10 months. Without getting into it too much, let's just say I can blame Cerner. Thanks also to a prod from a friend, here is an approach to a fairly common problem.
We all report calculated quantities out of our laboratories–quantities such as LDL cholesterol, non-HDL cholesterol, aldosterone:renin ratio, free testosterone, eGFR etc. How does one determine the precision (i.e. imprecision) of a calculated quantity. While earlier in my life, I might go to the trouble of trying to do such calculations analytically using the rules of error propagation, in my later years, I am more pragmatic and I'm happy to use a computational approach.
In this example, we will model the precision in calculated bioavailable testosterone (CBAT). Without explanation, I provide an R function for CBAT (and free testosterone) where testosterone is reported in nmol/L, sex hormone binding globulin (SHBG) is reported in nmol/L, and albumin is reported in g/L. Using the Vermeulen Equation as discussed in this publication, you can calculate CBAT as follows:
cbat <- function(TT,SHBG,ALB = 43){ Kalb <- 3.6*10^4 Kshbg <- 10^9 N <- 1 + Kalb*ALB/69000 a <- N*Kshbg b <- N + Kshbg*(SHBG - TT)/10^9 c <- -TT/10^9 FT <- (-b + sqrt(b^2 - 4*a*c))/(2*a)*10^9 cbat <- N*FT return(list(free.T = FT, cbat = cbat)) }
To sanity-check this, we can use this online calculator. Taking a typical male testosterone of 20 nmol/L, an SHBG of 50 nmol/L and an albumin of 43 g/L, we get the following:
cbat(20,50)
## $free.T ## [1] 0.3273049 ## ## $cbat ## [1] 7.670319
which is confirmed by the online calculator. Because the function is vectorized, we an submit a vector of testosterone results and SHBG results and get a vector of CBAT results.
cbat(c(10,20,30), c(40,50,60))
## $free.T ## [1] 0.1738837 0.3273049 0.4661380 ## ## $cbat ## [1] 4.074926 7.670319 10.923842
We now need some precision data for the three components. However, in our lab, we just substitute 43 g/L for the albumin, so we will leave that term out of the analysis and limit our precision calculation to testosterone and SHBG. This will allow us to present the precision as surface plots as a function of total testosterone and SHBG.
We do testosterone by LC-MS/MS using Deborah French's method. In the last three months, the precision has been 3.9% at 0.78 nmol/L, 5.5% at 6.7 nmol/L, 5.2% at 18.0 nmol/L, and 6.0% at 28.2 nmol/L. We are using the Roche Cobas e601 SHBG method which, according to the package insert, has precision of 1.8% at 14.9 nmol/L, 2.1 % at 45.7 nmol/L, and 4.0% at 219 nmol/L.
cv.tt <- c(3.9, 5.5, 5.2, 6.0) conc.tt <- c(0.78, 6.7, 18.0, 28.2) tt.df <- data.frame(conc.tt,cv.tt) plot(cv.tt ~ conc.tt, data = tt.df, main = "Precision Profile of Testosterone", xlab = "Testosterone (nmol/L)", ylab = "CV Testosterone (%)", ylim = c(0,8), type = "o")
cv.shbg <- c(1.8, 2.1, 4.0) conc.shbg <- c(14.9,45.7,219) shbg.df <- data.frame(cv.shbg, conc.shbg) plot(cv.shbg ~ conc.shbg, data = shbg.df, main = "Precision Profile of SHBG", xlab = "SHBG (nmol/L)", ylab = "CV SHGB (%)", ylim = c(0,5), type = "o")
We will want to generate linear interpolations of these precision profiles. Generally, we might watnt to use non-linear regression to do this but I will just linearly interpolate with the approxfun()
function. This will allow us to just call a function to get the approximate CV at concentrations other than those for which we have data.
tt.fun <- approxfun(x = tt.df$conc.tt, y = tt.df$cv.tt) shbg.fun <- approxfun(x = shbg.df$conc.shbg, y = shbg.df$cv.shbg)
Now, if we want to know the precision of SHBG at, say, 100 nmol/L, we can just write,
shbg.fun(100)
## [1] 2.695326
to obtain our precision result.
Now let's build a grid of SHBG and total testosterone (TT) values at which we will calculate the precision for CBAT.
shbg <- seq(from = 15, to = 200, by = 5) tt <- seq(from = 1, to = 28, by = 1)
At each point on the grid, we will have to generate, say, 100000 random TT values and 100000 random SHBG values with the appropriate precision and then calculate the expected precision of CBAT at those concentrations.
Let's do this for a single pair of concentrations by way of example modelling the random analytical error as Gaussian using the rnorm()
function.
# [SHBG] = 15 nmol/L # [TT] = 5.0 nmol/L set.seed(100) #just to get consistent results rng.tt <- rnorm(100000, mean = 5.0, sd = tt.fun(5.0)/100*5.0) rng.shbg <- rnorm(100000, mean = 15, sd = shbg.fun(15)/100*15) rng.cbat <- cbat(rng.tt, rng.shbg) cv.cbat <- sd(rng.cbat$cbat)/mean(rng.cbat$cbat)*100 cv.cbat
## [1] 5.30598
So, we can build the process of calculating the CV of CBAT into a function as follows:
cbat.cv <- function(TT, SHBG, N = 100000){ rng.tt <- rnorm(N, mean = TT, sd = tt.fun(TT)/100*TT) rng.shbg <- rnorm(N, mean = SHBG, sd = shbg.fun(SHBG)/100*SHBG) rng.cbat <- cbat(rng.tt, rng.shbg) cv <- sd(rng.cbat$cbat)/mean(rng.cbat$cbat)*100 return(cv) }
Now, we can make a matrix of the data for presenting a plot, calculating the CV and appending it to the dataframe.
cv.grid <- expand.grid(tt, shbg) names(cv.grid) <- c("tt", "shbg") cv.grid$cv.cbat <- mapply(cbat.cv, cv.grid$tt, cv.grid$shbg)
Now make plot using the wireframe()
function.
library(lattice) wireframe(cv.cbat ~ tt*shbg, data = cv.grid, xlab = "Testo \n (nmol/L)", ylab = "SHBG \n (nmol/L)", zlab = "CV \n (%)", drape = TRUE, colorkey = TRUE, col.regions = colorRampPalette(c("blue", "red", "yellow"))(100), scales = list(arrows=FALSE,cex=.5,tick.number = 10) )
This shows us that the CV of CBAT ranges from about 4–8% over the TT and SHBG ranges we have looked at.
We have determined the CV of calculated bioavailable testosterone using random number simulations using empirical CV data and produced a surface plot of CV. This allows us to comment on the CV of this lab reportable as a function of the two variables by which it is determined.
Parting Thought on Monte Carlo Simulations
The die is cast into the lap, but its every decision is from the LORD.
(Prov 16:33)
]]>There are a few ways to approach the problem of a conditionally formatted table in R. You can use the ReporteRs package's FlexTable()
function, the formattable package, or the condformat package. These allow you to produce a conditionally formatted tables in HTML. You can also use xtable package and essentially program what you want in LaTeX via the xtable()
function.
In my desire for something simple-ish, I am going do this graphically using the image()
function as suggested here. The benefit is that I can then push the table into an RMarkdown generated PDF document easily.
Suppose that you want to prepare a summary of how resident and medical student orders are placed on various wards. You obtain data that is formatted in the following manner.
head(orders,10)
## ward order.type cosigned ## 1 Med CPOE TRUE ## 2 Med Written FALSE ## 3 Med CPOE TRUE ## 4 Med Written TRUE ## 5 Med Written TRUE ## 6 Med Written TRUE ## 7 Med CPOE TRUE ## 8 Med CPOE FALSE ## 9 Med CPOE TRUE ## 10 Med CPOE TRUE
There are 4 wards: medicine, surgery, ER and orthopedics. Orders can come in as computerized physician order entry (CPOE), verbal or written. The orders have to be cosigned by staff and this is recorded as TRUE/FALSE because staff are not always compliant in logging on to the EMR to cosign the trainee orders.
str(orders)
## 'data.frame': 550 obs. of 3 variables: ## $ ward : Factor w/ 4 levels "Med","Surg","ER",..: 1 1 1 1 1 1 1 1 1 1 ... ## $ order.type: Factor w/ 3 levels "CPOE","Verbal",..: 1 3 1 3 3 3 1 1 1 1 ... ## $ cosigned : logi TRUE FALSE TRUE TRUE TRUE TRUE ...
summary(orders)
## ward order.type cosigned ## Med :150 CPOE :291 Mode :logical ## Surg:100 Verbal : 54 FALSE:195 ## ER :200 Written:205 TRUE :355 ## Orth:100 NA's :0
Let's start with the assumption that we want to apply the same conditional formatting to all data in the table. That is, we want to color code all results with the same algorithm. We can used the image()
function to get this done. Let's display the rates at which different order types (CPOE, verbal,or written) from the four wards. We can generate the proportions table in percent very easily with the prop.table()
and table()
functions operating on the first two columns of our orders
data:
my.data <- round(prop.table(table(orders[,1:2]),1)*100,1) my.data
## order.type ## ward CPOE Verbal Written ## Med 49.3 8.7 42.0 ## Surg 30.0 4.0 66.0 ## ER 89.5 7.0 3.5 ## Orth 8.0 23.0 69.0
The image()
function produces a tile plot based on matrix of z values, where z = f(x,y) using colours we can define and thresholds for switching from one colour to the next based on a breaks
parameter. In our case, we will say that if the result is less than equal to 25%, we will colour the tile blue, if it is greater than 25% but less than or equal to 50%, we will colour it red, and if it greater than 50%, it will be yellow.
You will note that we have to transpose the data with the t()
function because the image function plots the rows on the x axis on the columns on the y axis. You will also notice that we need to plot y descending on the y-axis to account for the fact that our tabular data has increasing index going down but the tile plot will default to have increasing y going up. We can also need to suppress the axes and their labels. The reader can comment out the lines xaxt = 'n'
and yaxt = 'n'
to see what is going on in terms of x and y values.
x = 1:ncol(my.data) y = 1:nrow(my.data) centers <- expand.grid(y,x) #make the plot margins a little bigger par(mar = c(2,7,4,2)) image(x, y, t(my.data), col = c(rgb(0,0,1,0.3),rgb(1,0,0,0.3), rgb(1,1,0,0.3)), breaks = c(0, 25, 50, 100), xaxt = 'n', yaxt = 'n', xlab = '', ylab = '', ylim = c(max(y) + 0.5, min(y) - 0.5) )
Now we can write our values over top with the text()
function.
text(centers[,2], centers[,1], c(my.data), col= "black")
And then we can write the variable names (which we yank from the attributes of the table) into the figure margin and draw some lines to make it look pretty. It was necessary to use the adj
and padj
parameters to make it look a little cleaner.
#add margin text mtext(paste(attributes(my.data)$dimnames[[2]],"(%)"), at=1:ncol(my.data), padj = -1) mtext(attributes(my.data)$dimnames[[1]], at=1:nrow(my.data), side = 2, las = 1, adj = 1.2) #add black lines abline(h=y + 0.5) abline(v=x + 0.5)
Now, if you want to make the text colour match the background colour, we will need a little function.
color.picker <- function(z){ if(z <= 25){return("blue")} else if( z > 25 & z <= 50){return("red")} else {return("darkorange4")} }
and then apply it over the values of the matrix:
text.cols <- sapply(c(my.data), color.picker) text(centers[,2], centers[,1], c(my.data), col= text.cols)
Now suppose you wanted different conditional formatting for each column. This is kind of a pain because you will need to provide the image()
function a matrix to generate an appropriate fill-colour and a different matrix for the data to be written in each cell. Let's imagine for example that we want to include the compliance rate for co-signing in a fourth column and this is the only column we want coloured. To this column we want a colour scheme applied wherein if compliance is less than or equal to 20%, the colour is red, between 20% and 80%, it is yellow, and above 80% it is green.
We can calculate a proportions table based on columns 1 and 3 of the orders
dataframe and then we can define a matrix fill.data
that has NA
on all the rates we calculated above.
my.data <- cbind(my.data,Cosigned = round(prop.table(table(orders[,c(1,3)]),1)*100,1)[,2]) fill.data <- my.data fill.data[,1:3] <- matrix(NA, nrow = nrow(my.data), ncol = ncol(my.data) - 1)
Now the proportions matrix is as follows:
my.data
## CPOE Verbal Written Cosigned ## Med 49.3 8.7 42.0 75.3 ## Surg 30.0 4.0 66.0 52.0 ## ER 89.5 7.0 3.5 88.5 ## Orth 8.0 23.0 69.0 13.0
and the fill data is:
fill.data
## CPOE Verbal Written Cosigned ## Med NA NA NA 75.3 ## Surg NA NA NA 52.0 ## ER NA NA NA 88.5 ## Orth NA NA NA 13.0
Now we can apply the image()
function to the fill.data
matrix. When it comes to writing the data in the cells, we will use the original my.data
matrix and we will adjust out color.picker()
function.
color.picker <- function(z){ if(is.na(z)){return("black")} else if(z <= 20){return("red")} else if( z > 20 & z <= 80){return("darkorange4")} else {return("darkgreen")} } x = 1:ncol(my.data) y = 1:nrow(my.data) centers <- expand.grid(y,x) par(mar = c(2,7,4,2)) image(x, y, t(fill.data), col = c(rgb(1,0,0,0.3),rgb(1,1,0,0.3), rgb(0,1,0,0.3)), breaks = c(0, 20, 80, 100), xaxt='n', yaxt='n', xlab='', ylab='', ylim = c(max(y) + 0.5, min(y) - 0.5) ) #write in values text.cols <- sapply(c(fill.data), color.picker) text(centers[,2], centers[,1], format(c(my.data),nsmall = 1), col= text.cols) #add margin text mtext(paste(attributes(my.data)$dimnames[[2]],"(%)"), at=1:ncol(my.data), padj = -1) mtext(attributes(my.data)$dimnames[[1]], at=1:nrow(my.data), side = 2, las = 1, adj = 1.2) #add black lines abline(h=y + 0.5) abline(v=x + 0.5)
So, it looks like this could become super–awkward if we had elaborate conditions to apply. This is where a packages like condformat and formattable come in handy. If you use the condformat package, you can include the table in an RMarkdown generated PDF or HTML document. However, the formattable()
function, though capable of much prettier output, does not work with PDFs generated using RMarkdown.
First, here is a condformat example. Suppose we wanted to colourized CPOE in shades of green because CPOE is more operationally desirable and verbal/written orders in shades of red because they are less operationally desirable. We also want the red/yellow/green formatting in the Cosigned column. Using condformat we could do the following:
library(condformat) my.data <- as.data.frame(my.data) color.picker <- function(z){ if(is.na(z)){return(0)} else if(z <= 20){return(1)} else if( z > 20 & z <= 80){return(2)} else {return(3)} } condformat(my.data) + rule_fill_gradient(CPOE, low = rgb(1,1,1), high = rgb(0,1,0)) + rule_fill_gradient(Verbal, low = rgb(1,1,1), high = rgb(1,0,0)) + rule_fill_gradient(Written, low = rgb(1,1,1), high = rgb(1,0,0)) + rule_fill_discrete(Cosigned, expression = sapply(Cosigned, color.picker),colours=c("0" = "white", "1" = "red", "2" = "yellow", "3" = "lightgreen"))
CPOE | Verbal | Written | Cosigned | |
---|---|---|---|---|
1 | 49.3 | 8.7 | 42.0 | 75.3 |
2 | 30.0 | 4.0 | 66.0 | 52.0 |
3 | 89.5 | 7.0 | 3.5 | 88.5 |
4 | 8.0 | 23.0 | 69.0 | 13.0 |
You can see that the rownames are suppressed with condformat()
. You could circumvent this by putting the rownames into their own column. This package is pretty easy to use and with PDF rendering (shown below) it produces something more LaTeX-ish than what is shown above which was generated straight to HTML.
For something more attractive looking, here is an example of something similar using the formattable package (borrowing heavily from the code author's examples ):
library(formattable) color.picker <- function(z){ if(is.na(z)){return("black")} else if(z <= 20){return("red")} else if( z > 20 & z <= 80){return("darkorange")} else {return("darkgreen")} } bg.picker <- function(z){ if(is.na(z)){return("black")} else if(z <= 20){return("pink")} else if( z > 20 & z <= 80){return("yellow")} else {return("lightgreen")} } my.data <- as.data.frame(my.data) formattable(my.data, list( CPOE = color_tile("white", "green"), Verbal = color_tile("white", "red"), Written = color_tile("white", "red"), Cosigned = formatter("span", style = x ~ style(display = "block", "border-radius" = "4px", "padding-right" = "4px", color = sapply(x,color.picker), "background-color" = sapply(x,bg.picker)), x ~ sprintf("%.2f (rank: %02d)", x, rank(-x))) ))
CPOE | Verbal | Written | Cosigned | |
---|---|---|---|---|
Med | 49.3 | 8.7 | 42.0 | 75.30 (rank: 02) |
Surg | 30.0 | 4.0 | 66.0 | 52.00 (rank: 03) |
ER | 89.5 | 7.0 | 3.5 | 88.50 (rank: 01) |
Orth | 8.0 | 23.0 | 69.0 | 13.00 (rank: 04) |
I hope that this points you in the right direction.
And as for conditions:
“If you declare with your mouth, “Jesus is Lord,” and believe in your heart that God raised him from the dead, you will be saved.”
Romans 10:9
]]>In two previous posts, I discussed visualizing your turnaround times (TATs). These posts are here and here. One other nice way to visualize your TAT is by means of a heatmap. In particular, we would like to look at the TAT for every hour of the week in a single figure. This manner of dataviz bling seems to be particularly attractive to managers because it costs you $0 to do this with R, but with commercial tools like Tableau, you'd have to pay a fortune and, as with Excel, your report would not be readily reproducible. Further, to make it autogenerate a PDF would mean you had to fork out more money for a report-generation module. Pffft.
We're going to read in a year's worth of order times and result times for a stat immunoassay test offered to a particular ward. The data, as I've formatted it, has two columns, ord and res.
test.data <- read.csv("test_data.csv") head(test.data)
## ord res ## 1 2015-01-01 13:24:00 2015-01-01 14:29:00 ## 2 2015-01-01 06:16:00 2015-01-01 07:43:00 ## 3 2015-01-01 06:32:00 2015-01-01 07:43:00 ## 4 2015-01-01 06:32:00 2015-01-01 07:43:00 ## 5 2015-01-01 12:12:00 2015-01-01 13:13:00 ## 6 2015-01-01 12:12:00 2015-01-01 13:13:00
Now, of course, we want to look at data collected from a long period of time so that we can be sure that the observations we are not simply an artifact of recent instrument downtime, maintenance, or whoever happened to be running the instrument. This is why I chose a year's worth of data. We are going to visualize the median order-to-file TAT for this test.
To calculate the hourly medians, we'll need to be able to label every TAT with the day it was run and the hour in the day it was run. This is pretty easy with the lubridate package. We'll do three things:
difftime()
function to calculate the TATswday()
function to determine which day of the week the specimen was run onformat()
function.library("dplyr") library("lubridate") library("fields") library("magrittr") test.data$ord <- ymd_hms(test.data$ord) test.data$res <- ymd_hms(test.data$res) test.data <- mutate(test.data,otf = difftime(res,ord,units="min")) test.data <- mutate(test.data,dow = wday(ord)) test.data <- mutate(test.data,hod = as.numeric(format(test.data$ord, "%H")))
And now the data will look like this:
head(test.data)
## ord res otf dow hod ## 1 2015-01-01 13:24:00 2015-01-01 14:29:00 65 mins 5 13 ## 2 2015-01-01 06:16:00 2015-01-01 07:43:00 87 mins 5 6 ## 3 2015-01-01 06:32:00 2015-01-01 07:43:00 71 mins 5 6 ## 4 2015-01-01 06:32:00 2015-01-01 07:43:00 71 mins 5 6 ## 5 2015-01-01 12:12:00 2015-01-01 13:13:00 61 mins 5 12 ## 6 2015-01-01 12:12:00 2015-01-01 13:13:00 61 mins 5 12
where the order-to-file TAT is in the otf column, the day-of-week is in the dow column and the hour-of-day is in the hod column. Now we can cycle though the days of the week and the hours of the day and calculate the year's median TAT for each hour, storing it in a matrix:
#prepare an empty matrix heat.data <- matrix(rep(NA,7*24),nrow = 7, ncol = 24) #loop over the days and hours and calculate the median TAT for(i in 1:7){ for(j in 0:23){ heat.data[i,j+1] <- subset(test.data, test.data$dow==i & test.data$hod==j)$otf %>% median } }
There are many ways to make the heatmap but I am particularly fond of the appearance of surface plots made with the fields package.
image.plot(1:7,seq(from=0.5, to=23.5, by = 1),heat.data,axes=FALSE, xlab = "Day of Week", ylab = "Hour of Day", ylim=c(0,24)) # the following pointless command is necessary to make the custom axis labels non-transparent # google revealed this among a number of other workarounds. points(0,0) # now these will display properly axis(side=1, at=1:7, labels=as.character(wday(1:7, label=TRUE)), las=2, cex.axis = 0.8) axis(side=2, at= 0:24, labels=0:24, las=1, cex.axis=0.8)
We can see that there is a morning slowdown that is particularly bad on Saturday. But what if we wanted to know the exact value for these eye-catching problem times? We'd have trouble, unless we overlaid some text.
It turns out that if you use white printing, you can't read the numbers when the background colour is yellow and green. There is a 64 colour gradient used in the image.plot()
function, so I calculated which integers in 0–64 were the problem and found the TATs that would correspond. It turned out that colours 20–45 out of the 64 colours in the gradient are the problem. By this means, I can make the printing black over the yellows and greens but white everywhere else:
image.plot(1:7,seq(from=0.5, to=23.5, by = 1),heat.data,axes=FALSE, xlab = "Day of Week", ylab = "Hour of Day", ylim=c(0,24)) points(0,0) #random command that resets par axis(side=1, at=1:7, labels=as.character(wday(1:7, label=TRUE)), las=2, cex.axis = 0.8) axis(side=2, at= 0:24, labels=0:24, las=1, cex.axis=0.8) # calculate the lowest and highest TAT min.z <- min(heat.data) max.z <- max(heat.data) # determine which TAT's will have yellow to green shading z.yellows <- min.z + (max.z - min.z)/64*c(20,45) # print the labels for(i in 1:7){ for(j in 1:24){ if((heat.data[i,j] > z.yellows[1])&(heat.data[i,j] < z.yellows[2])){ text(i,j-0.5,heat.data[i,j], col="black", cex = 0.8) }else{ text(i,j-0.5,heat.data[i,j], col="white", cex = 0.8) } } }
So, that is not too bad, and if you wanted to look at the 75th percentile instead you would only have to adjust the heat.data calculation as follows:
#prepare an empty matrix heat.data <- matrix(rep(NA,7*24),nrow = 7, ncol = 24) #loop over the days and hours and calculate the median TAT for(i in 1:7){ for(j in 0:23){ heat.data[i,j+1] <- subset(test.data, test.data$dow==i & test.data$hod==j)$otf %>% quantile(.,probs=0.75) } }
And this is what you will get.
Hmmm…we'd better look at Saturday morning, 6 am. I hope you have found this helpful.
And as for heat
“He will sit as a refiner and purifier of silver”
Malachi 3:3
]]>As you know in Clinical Chemistry, we are not always writing a major paper but sometimes just preparing a short-report to answer a technical question that we've encounted at work. For shorter papers, journals often have more stringent rules about how many figures you can submit and even sometimes forbid multipanelled figures. In these situations, we might want to cram a little more into your figure than we might otherwise. In a recent submission, I wanted to produce a difference plot of immunoassay results before and after storage but I also wanted to show the distribution of the results using a histogram–but this would have counted as two separate figures.
However, thanks to some fine work by Dean Attali of UBC Department of Statistics where he works with R-legend Jenny Bryan, it is quite easy to add marginal histograms to a Bland Altman (or any other scatter) plot using the ggExtra package.
Let's make some fake data for a Bland Altman plot. Let's pretend that we are measuring the same quantity by immunoassay at baseline and after 1 year of storage at -80 degrees. We'll add some heteroscedastic error and create some apparent degradation of about 20%:
set.seed(10) #make predictable random data baseline <- rlnorm(100, 0, 1) post <- 0.8*baseline + rnorm(100, 0, 0.10*baseline) plot(baseline,post) abline(lm(post ~ baseline)) abline(0, 1, col="red", lty = 2)
Or if we plot this in the ggplot()
paradigm
library(ggplot2) my.data <- data.frame(baseline, post) ggplot(my.data, aes(x=baseline, y=post)) + theme_bw() + geom_point(shape=1) + # Use hollow circles geom_smooth(method=lm) + # Add linear regression line geom_abline(slope = 1, intercept = 0, linetype = 2, colour = "red")
Now we will prepare the difference data:
diff <- (post - baseline) diffp <- (post - baseline)/baseline*100 sd.diff <- sd(diff) sd.diffp <- sd(diffp) my.data <- data.frame(baseline, post, diff, diffp)
In standard Bland Altman plots, one plots the difference between methods against the average of the methods, but in this case, the x-axis should be the baseline result, because that is the closest thing we have to the truth.
library(ggExtra) diffplot <- ggplot(my.data, aes(baseline, diff)) + geom_point(size=2, colour = rgb(0,0,0, alpha = 0.5)) + theme_bw() + #when the +/- 2SD lines will fall outside the default plot limits #they need to be pre-stated explicitly to make the histogram line up properly. #Thanks to commenter for noticing this. ylim(mean(my.data$diff) - 3*sd.diff, mean(my.data$diff) + 3*sd.diff) + geom_hline(yintercept = 0, linetype = 3) + geom_hline(yintercept = mean(my.data$diff)) + geom_hline(yintercept = mean(my.data$diff) + 2*sd.diff, linetype = 2) + geom_hline(yintercept = mean(my.data$diff) - 2*sd.diff, linetype = 2) + ylab("Difference pre and post Storage (mg/L)") + xlab("Baseline Concentration (mg/L)") #And now for the magic - we'll use 25 bins ggMarginal(diffplot, type="histogram", bins = 25)
So that is the difference plot for the absolute difference. We can also obviously do the percent difference.
diffplotp <- ggplot(my.data, aes(baseline, diffp)) + geom_point(size=2, colour = rgb(0,0,0, alpha = 0.5)) + theme_bw() + geom_hline(yintercept = 0, linetype = 3) + geom_hline(yintercept = mean(my.data$diffp)) + geom_hline(yintercept = mean(my.data$diffp) + 2*sd.diffp, linetype = 2) + geom_hline(yintercept = mean(my.data$diffp) - 2*sd.diffp, linetype = 2) + ylab("Difference pre and post Storage (%)") + xlab("Baseline Concentration (mg/L)") ggMarginal(diffplotp, type="histogram", bins = 25)
You can also do this in a non-ggplot()
paradigm using base plotting utilities as described in this R-bloggers post.
And that, friends, is a way of squishing in a histogram of your sample concentrations into your difference plot which allows you to graphically display your sampling distribution and justify whether you would use parametric or non-parametric statistics to assess the extent of loss of immunoreactivity from storage.
And speaking of scatterplots
“…then the Lord your God will restore your fortunes and have compassion on you and gather you again from all the nations where he scattered you.”
Deut 30:3
Back in 2011 I was not aware of any tool in R for Passing Bablok (PB) regression, a form of robust regression described in a series of three papers in Clinical Chemistry and Laboratory Medicine (then J Clin Chem and Biochem) available here, here and here. For reasons that are not entirely clear to me, this regression methodology is favoured by clinical chemists but seems largely ignored by other disciplines. However since reviewers clinical chemistry journals will demand the use of PB regression, it seemed expeditious to me to code it in R. This is what spawned a small project for a piece of software to do PB (and Deming and ordinary least squares) regression using a self-contained executable that could be downloaded, unzipped on a Windows Desktop and just ran. You can download here and instructions for installation and use are here and here respectively. The calculations are all done in R, the GUI is built with Python and Py-Qt4 and the executable with cx_freeze. I made it run without an installer because hospital IT often refuse to install software that has not been officially vetted and purchased. The tool was a lot more popular than I anticipated now having about 2000 downloads. In any case, maintenance, upgrades, bug fixing and dealing with operating system updates that break things (like OSX El Capitan's security policies) are no-fun so a Shiny based solution to the same problem makes a lot of sense.
Since 2011, statisticians at Roche Diagnostics programmed the mcr package for PB and Deming regression. Additionally, there is also the MethComp package and the deming package from the Mayo Clinic which both offer PB regression.
Enter Burak Bahar, a like-minded Clinical Pathologist who is currently doing a fellowship at Yale. He liked my cp-R program but he saw the need for a web-based equivalent.
Burak and his wife Ayse, also a physician, have coded a Shiny App for doing Deming, PB and least squares regression in R which is capable of producing publication quality figures and provides all the regression statistics you would need for method-validation or publication. It can also produce a regression report in PDF, Word or HTML. The dynamic duo of the Bahar-MDs deserve all credit here as my only contribution related to suggestions related to usability. This project was presented at the 2016 American Association of Clinical Chemistry meeting in Philadelphia.
The app URL is bahar.shinyapps.io/method_compare. Go to the data tab on the left and then cut and paste your data from an spreadsheet program. Shortcuts CTRL-C (copy) and CTRL-V (paste) work natively in the table. The table is pre-populated with some random data for demonstration purposes. Once your data is pasted in, click on the Plots tab and choose the Bland-Altman or Scatter Plot.
Here is an image generated with the Bahar Shiny app using method comparison data obtained from St. Paul's Hospital Laboratory in migrating from Siemens Immulite 2000 XPi to Roche Cobas e601 for Calcitonin determination. Don't worry, we did more than 33 comparison–I am just showing the low end.
Try adjusting some of the plot parameters. The figures will update in real time. Thanks to Burak and Ayse Bahar for your work!
(Dan's) Parting Thought
There are straight lines that matter a lot more than regression.
I will make justice the measuring line and righteousness the plumb line
(Isa 28:17)
As Clinical Pathologists we work hard to create laboratory developed tests (LDTs) using liquid chromatography and tandem mass spectrometry (LC-MS/MS) that are robust, repeatable, accurate and have a wider dynamic range than commercial immunoassays. In our experience, properly developed LC-MS/MS assays are much less expensive and outperform their commercial immunoassay counterparts from an analytical standpoint.
However, despite mass spectrometry's communal obsession with analytical performance of our LDTs, sometimes we overlook the matter of handling the data we generate. Unlike traditional diagnostic companies (e.g. Siemens, Roche) who take care of upload and download of patient data and results via HL7 streams to the laboratory information system (LIS), mass spectrometry companies have not yet made this a priority. This leaves us either paying out a lot of money for custom middleware solutions or manually transcribing our LC-MS/MS results.
We might naively think, “How bad can the transcription be?” but over time, it becomes painfully evident that manual transcription of result is tedious, error–prone and inefficient use of tech–time.
Many LIS vendors offer what is called a “flat-file interface”. In this case, there is no HL7 stream generated using a communication socket between instrument and LIS. Rather, the results are saved in an ASCII text file with a pre-defined format and then transferred to the LIS via a secure shell (SSH) connection.
For this post, we are going to take some sample flat files from a SCIEX API5000 triple quadrupole mass spectrometer and prepare a flat file for the SunQuest LIS. Please note that this code is provided to you as is under the GNU Public Licence and without any guarantee. You know how all the LC-MS/MS vendors say their instruments are for “research use only”? –yeah, I'm giving this to you in the same spirit. If you use or modify it, you do so at your own risk. Any changes to how your flatfile is generated by your mass spectrometer or any upgrades to your LC-MS/MS software could make this code malfunction. You have been warned.
SunQuest requires the output file to be a comma separated values (CSV) file with a unique specimen or internal QC result in each row. The first column is the instrument ID, the second columns is the specimen container ID (an E followed by a 10–digit integer), the third is testcode and the fourth is the result. The file itself is required to have a time–stamp so that it has a traceable name and should have no header. For an instrument named PAPI (short for Providence API 5000) and a testcode TES (for testosterone), the file might look like this:
PAPI,E2324434511,TES,3.12 PAPI,E2324434542,TES,8.75 PAPI,E2324434565,TES,25.34 ...
After we have completed an analytical run and reviewed all peaks to generate our fileable results, we can export the quatified sample batch to an ASCII text file. The file contains a whole lot of diagnostic information about the run like which multiple reaction monitoring (MRM) transitions we used, what the internal standard (IS) counts were, results from the quantifier and qualifier ion, fitted values for the calibrators etc. There are more than 80 columns in a typical file and we could talk about all the things we might do with this data but in this case, we are concerned with extracting and preparing the results file.
If we are actually going to make an R script usable by a human, it would be good to be able to choose which file we want to process and what test we want to extract using a simple graphical user interface (GUI). There are a number of tools one can use to build GUIs in R but the most rudimentary is TclTk. I have to confess that I find the language constructs for GUI creation both non–intuitive and boring. For this reason, I present without discussion, a modification of a recipe for creating a box with radio–buttons. We are going to choose which of three analytes (you can increase this number as you please) for which we wish to process a flat–file. These are: aldosterone, cortisol and testosterone. Please note that if you execute this code on a Mac, you will have to install XQuartz because Macs don't have native X-windows support despite the BSD Linux heritage of OSX.
library(tcltk2) #make a radiobutton widget #source for tk widget modifed from http://www.sciviews.org/recipes/tcltk/TclTk-radiobuttons/ #accessed Feb 10, 2016 win1 <- tktoplevel() win1$env$rb1 <- tk2radiobutton(win1) win1$env$rb2 <- tk2radiobutton(win1) win1$env$rb3 <- tk2radiobutton(win1) rbValue <- tclVar("Aldosterone") tkconfigure(win1$env$rb1, variable = rbValue, value = "Aldosterone") tkconfigure(win1$env$rb2, variable = rbValue, value = "Cortisol") tkconfigure(win1$env$rb3, variable = rbValue, value = "Testosterone") tkgrid(tk2label(win1, text = "Which analyte are you processing?"), columnspan = 2, padx = 10, pady = c(15, 5)) tkgrid(tk2label(win1, text = "Aldosterone"), win1$env$rb1, padx = 10, pady = c(0, 5)) tkgrid(tk2label(win1,text = "Cortisol"), win1$env$rb2, padx = 10, pady = c(0, 5)) tkgrid(tk2label(win1,text = "Testosterone"), win1$env$rb3, padx = 10, pady = c(0, 15)) onOK <- function() { rbVal <- as.character(tclvalue(rbValue)) tkdestroy(win1) } win1$env$butOK <- tk2button(win1, text = "OK", width = -6, command = onOK) tkgrid(win1$env$butOK, columnspan = 2, padx = 10, pady = c(5, 15)) tkfocus(win1) #this final line is necessary to prevent to the program from proceeding until this radio button widget has closed tkwait.window(win1)
This will give us the following pop-up window with radiobuttons in which I have selected testosterone.
You will notice that Tk windows do not appear native to the operating system. We can live with this because we are not shallow.
After you hit the OK button, the Tk widget then puts the chosen value into an Tk variable called rbValue
. We can determine the value using the command tclvalue(rbValue)
. The reason we need to know which analyte we are working with is because the name of the MRM we want to pull out of the flat file is dependent on the analyte of course. We will also need to replace results below the limit of quantitation (LoQ) with “< x”, whatever x happens to be, which will be a different threshold for each analyte.
In our case, the testcodes for aldosterone, cortisol and testosterone are ALD,CORT and TES respectively, the LoQs are 50 pmol/L, 1 nmol/L and 0.05 nmol/L and the MRM names are “Aldo 1”, “Aldo 2”, “Cortisol 1”, “Cortisol 2” and “Testo 1” and “Testo 2” as we defined them within SCIEX Analyst Software. We will use the switch()
function to define three variables (test.code
, LoQ
, and MRM.names
) which we will use later to process the flat–file. We will also define the name of the worksheet in a variable called worksheet
. These are the parameters you would have to change in order to modify the code for your purposes.
#set the testcode by test test.code <- switch(tclvalue(rbValue), "Aldosterone" = "ALD", "Testosterone" = "TES", "Cortisol" = "CORT" ) #set the LoQ by test LoQ <- switch(tclvalue(rbValue), "Aldosterone" = "<50", "Testosterone" = "<0.05", "Cortisol" = "<1" ) #set the MRM names by test MRM.names <- switch(tclvalue(rbValue), "Aldosterone" = c("Aldo 1", "Aldo 2"), "Testosterone" = c("Testo 1", "Testo 2"), "Cortisol" = c("Cortisol 1", "Cortisol 2") ) #set the worksheet name for your site worksheet <- "PAPI"
Now we will prompt the user to tell them that they are to choose an instrument flat–file and we will determine the path of the chosen file. We will need the path to both read in the appropriate file but also to write the output later.
#choose the flat file to process tkmessageBox(message="You are about to choose a flat file to process.") flat.file.path <- tk_choose.files(default = "", caption = "Select File", multi = FALSE, filters = NULL, index = 1) #determine the directory name of the chosen file flat.file.dir <- dirname(flat.file.path) #determine the file name of the chosen file flat.file.name <- basename(flat.file.path)
This code will create this message box:
and this file choice dialogue box:
and after a file is selected and the Open is pressed, the path to the flat–file is stored in the variable flat.file.path
.
So we chosen the file we want to read in but what does this file look like? To just get a gander at it, we could open it with Excel and see how it is laid out. But since we have broken up with Excel, we won't do this. SCIEX Analyst exports tab (not comma) delimited files. R has a built in function read.delim()
for reading these files but we will quickly discover that read.delim()
assumes the files have a rectangular structure, having the same number of columns in each row. R will make assumptions about the shape of the data file based on the first few rows and then try to read it in. In this case, it will fail and you will get gibberish. To get this to work for us we will need to tell R how many rows to skip before the real data starts or we will need to tell R the number of columns the file has (which is not guaranteed to be consistent between versions of vendor software). There are lots of ways to do this but I think the simplest is to use grep()
.
I did this by reading the file in with no parsing of the tabs using the readLines()
function. This function creates a vector for which each successive value is the entire content of the row of the file. I display the first 30 lines of the file. Suppose that we chose a testosterone flat file.
x <- readLines(flat.file.path) x[1:30]
## [1] "Peak Name: Testo-d3 2" ## [2] "Use as Internal Standard" ## [3] "Q1/Q3 Masses: 292.50/97.20 Da" ## [4] "" ## [5] "Peak Name: Testo 1" ## [6] "Internal Standard: Testo-d3 2" ## [7] "Q1/Q3 Masses: 289.50/97.20 Da" ## [8] "" ## [9] "Fit\tQuadratic\tWeighting\t1 / x\tIterate\tNo" ## [10] "a0\t0.00658" ## [11] "a1\t0.2" ## [12] "a2\t-0.000443" ## [13] "Correlation coefficient\t0.9999" ## [14] "Use Area" ## [15] "" ## [16] "Peak Name: Testo 2" ## [17] "Internal Standard: Testo-d3 2" ## [18] "Q1/Q3 Masses: 289.50/109.10 Da" ## [19] "" ## [20] "Fit\tQuadratic\tWeighting\t1 / x\tIterate\tNo" ## [21] "a0\t0.00359" ## [22] "a1\t0.17" ## [23] "a2\t-0.000313" ## [24] "Correlation coefficient\t0.9999" ## [25] "Use Area" ## [26] "" ## [27] "" ## [28] "" ## [29] "Sample Name\tSample ID\tSample Type\tSample Comment\tSet Number\tAcquisition Method\tAcquisition Date\tRack Type\tRack Position\tVial Position\tPlate Type\tPlate Position\tFile Name\tDilution Factor\tWeight To Volume Ratio\tSample Annotation\tDisposition\tAnalyte Peak Name\tAnalyte Units\tAnalyte Peak Area (counts)\tAnalyte Peak Area for DAD (mAU x min)\tAnalyte Peak Height (cps)\tAnalyte Peak Height for DAD (mAU)\tAnalyte Concentration (nmol/L)\tAnalyte Retention Time (min)\tAnalyte Expected RT (min)\tAnalyte RT Window (sec)\tAnalyte Centroid Location (min)\tAnalyte Start Scan\tAnalyte Start Time (min)\tAnalyte Stop Scan\tAnalyte Stop Time (min)\tAnalyte Integration Type\tAnalyte Signal To Noise\tAnalyte Peak Width (min)\tStandard Query Status\tAnalyte Mass Ranges (Da)\tAnalyte Wavelength Ranges (nm)\tArea Ratio\tHeight Ratio\tAnalyte Annotation\tAnalyte Channel\tAnalyte Peak Width at 50% Height (min)\tAnalyte Slope of Baseline (%/min)\tAnalyte Processing Alg.\tAnalyte Peak Asymmetry\tAnalyte Integration Quality\tIS Peak Name\tIS Units\tIS Peak Area (counts)\tIS Peak Area for DAD (mAU x min)\tIS Peak Height (cps)\tIS Peak Height for DAD (mAU)\tIS Concentration (nmol/L)\tIS Retention Time (min)\tIS Expected RT (min)\tIS RT Window (sec)\tIS Centroid Location (min)\tIS Start Scan\tIS Start Time (min)\tIS Stop Scan\tIS Stop Time (min)\tIS Integration Type\tIS Signal To Noise\tIS Peak Width (min)\tIS Mass Ranges (Da)\tIS Wavelength Ranges (nm)\tIS Channel\tIS Peak Width at 50% Height (min)\tIS Slope of Baseline (%/min)\tIS Processing Alg.\tIS Peak Asymmetry\tIS Integration Quality\tUse Record\tRecord Modified\tCalculated Concentration (nmol/L)\tCalculated Concentration for DAD (nmol/L)\tRelative Retention Time\tAccuracy (%)\tResponse Factor\tAcq. Start Time (min)\tInjection Volume used\t" ## [30] "Blank\t\tBlank\tBlankMPX_SAMPLE_ID:189001;Stream Number:2;Plate Code:Deep Well MTP 96 Cooled;Injection Volume:25;\t0\tTesto_DWP_S2.dam\t2/11/2013 5:06:45 PM\tDeep Well MTP 96 Cooled\t1\t1\tDeep Well MTP 96 Cooled\t2\t140305B1.wiff\t1.00\t0.00\t\t\tTesto 1\tnmol/L\t0\tN/A\t0.00e+000\tN/A\t0.00\t0.00\t1.29\t30.0\t0.00\t0\t0.00\t0\t0.00\tNo Peak\tN/A\t0.00\tN/A\t289.500/97.200 Da\tN/A\t0.00e+000\t0.00e+000\t\tN/A\t0.00\t0.00e+000\tSpecify Parameters - MQIII\t0.00\t0.00\tTesto-d3 2\tnmol/L\t158416\tN/A\t5.58e+004\tN/A\t1.00\t1.27\t1.29\t20.0\t1.28\t115\t1.18\t139\t1.43\tBase To Base\tN/A\t0.248\t292.500/97.200 Da\tN/A\tN/A\t4.36e-002\t1.06e+000\tSpecify Parameters - MQIII\t1.60\t0.956\t\t0\tN/A\tN/A\t0.00\tN/A\tN/A\t2.85\t25\t"
All of the \t
's that you see are the tabs in the file which are has read in literally when we use readLines()
. We can see that in this file nothing of use happens until line 29 but this is not consistent from file to file so we should not just assume that 29 is always the magic number where the good stuff begins. We can see that the line starting “Sample Name \t Sample ID” is the real starting point so we can determine how many lines to skip by using grep()
and prepare for some error–handling with a variable called problem
by which we can deal with the circumstance that no approriate starting row is identified.
skip.val <- grep("Sample Name\tSample ID", x, fixed = TRUE) - 1 #if no such row is found, then the wrong file has been chosen if (length(skip.val)==0){ problem <- TRUE } else { problem <- FALSE } skip.val
## [1] 28
Now that we know how many lines to skip we can read in the data:
my.data <- read.delim(flat.file.path, sep = "\t", strip.white = TRUE, skip = skip.val, header = TRUE, stringsAsFactors = FALSE)
We can have a look at the structure of this file
str(my.data)
## 'data.frame': 196 obs. of 83 variables: ## $ Sample.Name : chr "Blank" "Blank" "STD1" "STD1" ... ## $ Sample.ID : logi NA NA NA NA NA NA ... ## $ Sample.Type : chr "Blank" "Blank" "Standard" "Standard" ... ## $ Sample.Comment : chr "BlankMPX_SAMPLE_ID:189001;Stream Number:2;Plate Code:Deep Well MTP 96 Cooled;Injection Volume:25;" "BlankMPX_SAMPLE_ID:189001;Stream Number:2;Plate Code:Deep Well MTP 96 Cooled;Injection Volume:25;" "StandardMPX_SAMPLE_ID:189002;Stream Number:2;Plate Code:Deep Well MTP 96 Cooled;Injection Volume:25;" "StandardMPX_SAMPLE_ID:189002;Stream Number:2;Plate Code:Deep Well MTP 96 Cooled;Injection Volume:25;" ... ## $ Set.Number : int 0 0 0 0 0 0 0 0 0 0 ... ## $ Acquisition.Method : chr "Testo_DWP_S2.dam" "Testo_DWP_S2.dam" "Testo_DWP_S2.dam" "Testo_DWP_S2.dam" ... ## $ Acquisition.Date : chr "2/11/2013 5:06:45 PM" "2/11/2013 5:06:45 PM" "2/11/2013 5:13:14 PM" "2/11/2013 5:13:14 PM" ... ## $ Rack.Type : chr "Deep Well MTP 96 Cooled" "Deep Well MTP 96 Cooled" "Deep Well MTP 96 Cooled" "Deep Well MTP 96 Cooled" ... ## $ Rack.Position : int 1 1 1 1 1 1 1 1 1 1 ... ## $ Vial.Position : int 1 1 13 13 25 25 37 37 49 49 ... ## $ Plate.Type : chr "Deep Well MTP 96 Cooled" "Deep Well MTP 96 Cooled" "Deep Well MTP 96 Cooled" "Deep Well MTP 96 Cooled" ... ## $ Plate.Position : int 2 2 2 2 2 2 2 2 2 2 ... ## $ File.Name : chr "140305B1.wiff" "140305B1.wiff" "140305B1.wiff" "140305B1.wiff" ... ## $ Dilution.Factor : num 1 1 1 1 1 1 1 1 1 1 ... ## $ Weight.To.Volume.Ratio : num 0 0 0 0 0 0 0 0 0 0 ... ## $ Sample.Annotation : logi NA NA NA NA NA NA ... ## $ Disposition : logi NA NA NA NA NA NA ... ## $ Analyte.Peak.Name : chr "Testo 1" "Testo 2" "Testo 1" "Testo 2" ... ## $ Analyte.Units : chr "nmol/L" "nmol/L" "nmol/L" "nmol/L" ... ## $ Analyte.Peak.Area..counts. : int 0 0 5273 3464 19412 16195 37994 32722 87815 74821 ... ## $ Analyte.Peak.Area.for.DAD..mAU.x.min. : chr "N/A" "N/A" "N/A" "N/A" ... ## $ Analyte.Peak.Height..cps. : num 0 0 1830 1300 6620 5700 13600 11400 30900 26100 ... ## $ Analyte.Peak.Height.for.DAD..mAU. : chr "N/A" "N/A" "N/A" "N/A" ... ## $ Analyte.Concentration..nmol.L. : chr "0.00" "0.00" "0.108" "0.108" ... ## $ Analyte.Retention.Time..min. : num 0 0 1.29 1.29 1.29 1.28 1.29 1.29 1.29 1.29 ... ## $ Analyte.Expected.RT..min. : num 1.29 1.29 1.29 1.29 1.29 1.29 1.29 1.29 1.29 1.29 ... ## $ Analyte.RT.Window..sec. : num 30 30 30 30 30 30 30 30 30 30 ... ## $ Analyte.Centroid.Location..min. : num 0 0 1.3 1.29 1.29 1.29 1.3 1.3 1.3 1.29 ... ## $ Analyte.Start.Scan : int 0 0 119 120 119 118 120 120 119 119 ... ## $ Analyte.Start.Time..min. : num 0 0 1.22 1.23 1.22 1.21 1.23 1.23 1.22 1.22 ... ## $ Analyte.Stop.Scan : int 0 0 137 130 137 135 135 138 141 139 ... ## $ Analyte.Stop.Time..min. : num 0 0 1.41 1.33 1.41 1.39 1.39 1.42 1.45 1.43 ... ## $ Analyte.Integration.Type : chr "No Peak" "No Peak" "Base To Base" "Base To Base" ... ## $ Analyte.Signal.To.Noise : chr "N/A" "N/A" "N/A" "N/A" ... ## $ Analyte.Peak.Width..min. : num 0 0 0.186 0.103 0.186 0.176 0.155 0.186 0.227 0.207 ... ## $ Standard.Query.Status : chr "N/A" "N/A" "N/A" "N/A" ... ## $ Analyte.Mass.Ranges..Da. : chr "289.500/97.200 Da" "289.500/109.100 Da" "289.500/97.200 Da" "289.500/109.100 Da" ... ## $ Analyte.Wavelength.Ranges..nm. : chr "N/A" "N/A" "N/A" "N/A" ... ## $ Area.Ratio : num 0 0 0.0304 0.02 0.113 0.094 0.219 0.188 0.468 0.398 ... ## $ Height.Ratio : num 0 0 0.0304 0.0216 0.108 0.0933 0.225 0.189 0.471 0.398 ... ## $ Analyte.Annotation : logi NA NA NA NA NA NA ... ## $ Analyte.Channel : chr "N/A" "N/A" "N/A" "N/A" ... ## $ Analyte.Peak.Width.at.50..Height..min. : num 0 0 0.0447 0.0447 0.046 0.0432 0.0439 0.0454 0.0438 0.045 ... ## $ Analyte.Slope.of.Baseline....min. : num 0 0 16.4 23.2 2.89 7.54 4.65 3.46 0.631 3 ... ## $ Analyte.Processing.Alg. : chr "Specify Parameters - MQIII" "Specify Parameters - MQIII" "Specify Parameters - MQIII" "Specify Parameters - MQIII" ... ## $ Analyte.Peak.Asymmetry : num 0 0 1.8 0.874 1.83 1.41 1.51 2.18 2.18 2 ... ## $ Analyte.Integration.Quality : num 0 0 0.379 0.233 0.697 0.62 0.794 0.765 0.907 0.875 ... ## $ IS.Peak.Name : chr "Testo-d3 2" "Testo-d3 2" "Testo-d3 2" "Testo-d3 2" ... ## $ IS.Units : chr "nmol/L" "nmol/L" "nmol/L" "nmol/L" ... ## $ IS.Peak.Area..counts. : int 158416 158416 173383 173383 172263 172263 173811 173811 187783 187783 ... ## $ IS.Peak.Area.for.DAD..mAU.x.min. : chr "N/A" "N/A" "N/A" "N/A" ... ## $ IS.Peak.Height..cps. : num 55800 55800 60100 60100 61200 61200 60300 60300 65700 65700 ... ## $ IS.Peak.Height.for.DAD..mAU. : chr "N/A" "N/A" "N/A" "N/A" ... ## $ IS.Concentration..nmol.L. : num 1 1 1 1 1 1 1 1 1 1 ... ## $ IS.Retention.Time..min. : num 1.27 1.27 1.27 1.27 1.27 1.27 1.28 1.28 1.28 1.28 ... ## $ IS.Expected.RT..min. : num 1.29 1.29 1.29 1.29 1.29 1.29 1.29 1.29 1.29 1.29 ... ## $ IS.RT.Window..sec. : num 20 20 20 20 20 20 20 20 20 20 ... ## $ IS.Centroid.Location..min. : num 1.28 1.28 1.28 1.28 1.28 1.28 1.28 1.28 1.28 1.28 ... ## $ IS.Start.Scan : int 115 115 117 117 115 115 117 117 118 118 ... ## $ IS.Start.Time..min. : num 1.18 1.18 1.2 1.2 1.18 1.18 1.2 1.2 1.21 1.21 ... ## $ IS.Stop.Scan : int 139 139 140 140 140 140 139 139 139 139 ... ## $ IS.Stop.Time..min. : num 1.43 1.43 1.44 1.44 1.44 1.44 1.43 1.43 1.43 1.43 ... ## $ IS.Integration.Type : chr "Base To Base" "Base To Base" "Base To Base" "Base To Base" ... ## $ IS.Signal.To.Noise : chr "N/A" "N/A" "N/A" "N/A" ... ## $ IS.Peak.Width..min. : num 0.248 0.248 0.238 0.238 0.258 0.258 0.227 0.227 0.217 0.217 ... ## $ IS.Mass.Ranges..Da. : chr "292.500/97.200 Da" "292.500/97.200 Da" "292.500/97.200 Da" "292.500/97.200 Da" ... ## $ IS.Wavelength.Ranges..nm. : chr "N/A" "N/A" "N/A" "N/A" ... ## $ IS.Channel : chr "N/A" "N/A" "N/A" "N/A" ... ## $ IS.Peak.Width.at.50..Height..min. : num 0.0436 0.0436 0.0445 0.0445 0.0435 0.0435 0.0455 0.0455 0.0451 0.0451 ... ## $ IS.Slope.of.Baseline....min. : num 1.06 1.06 1.17 1.17 1.39 1.39 1.51 1.51 1.93 1.93 ... ## $ IS.Processing.Alg. : chr "Specify Parameters - MQIII" "Specify Parameters - MQIII" "Specify Parameters - MQIII" "Specify Parameters - MQIII" ... ## $ IS.Peak.Asymmetry : num 1.6 1.6 2.19 2.19 1.77 1.77 1.88 1.88 2.18 2.18 ... ## $ IS.Integration.Quality : num 0.956 0.956 0.971 0.971 0.968 0.968 0.969 0.969 0.97 0.97 ... ## $ Use.Record : int NA NA 1 1 1 1 1 1 1 1 ... ## $ Record.Modified : int 0 0 0 0 0 0 0 0 0 0 ... ## $ Calculated.Concentration..nmol.L. : chr "N/A" "N/A" "0.119" "0.0962" ... ## $ Calculated.Concentration.for.DAD..nmol.L.: chr "N/A" "N/A" "N/A" "N/A" ... ## $ Relative.Retention.Time : num 0 0 1.01 1.01 1.01 1.01 1.01 1.01 1.01 1.01 ... ## $ Accuracy.... : chr "N/A" "N/A" "111." "89.1" ... ## $ Response.Factor : chr "N/A" "N/A" "0.282" "0.185" ... ## $ Acq..Start.Time..min. : num 2.85 2.85 2.85 2.85 2.85 2.85 2.85 2.85 2.85 2.85 ... ## $ Injection.Volume.used : int 25 25 25 25 25 25 25 25 25 25 ... ## $ X : logi NA NA NA NA NA NA ...
And we see that there is lots of stuff we don't need. What we do need are the columns titled “Sample.Name” (which is the specimen container ID in this case), the “Analyte.Peak.Name” (which is the MRM, either quantifier or qualifier), and the one whose name starts with “Calculated.Concentration..”. The last of these also contains the units of measure which is analyte–dependent. To get rid of this analyte–dependence of the column name, we can find out which column this is and rename it:
conc.col.num <- grep("Calculated.Concentration..",names(my.data), fixed = TRUE) names(my.data)[conc.col.num]<- "Calculated.Concentration"
Now we can pull out the three columns of interest and put them into a dataframe named results.
#pull out the columns of interest results <- my.data[,c("Sample.Name", "Analyte.Peak.Name","Calculated.Concentration")] names(results) <- c("sampleID", "mrm", "conc")
Now we only need the quantifier ion results which we were defined by the user with Tk GUI, so we can pull them out with grep. I will pull out the qualifiers also but we do not need them unless we wanted to compute ion-ratios, for example.
#handle non-numeric results quantifiers <- results[grep(MRM.names[1], results$mrm),] quantifiers$conc <- as.numeric(quantifiers$conc)
## Warning: NAs introduced by coercion
qualifiers <- results[grep(MRM.names[2], results$mrm),] qualifiers$conc <- as.numeric(qualifiers$conc)
## Warning: NAs introduced by coercion
Having pulled out the MRM of interest, we can define which rows correspond to standards, QC and patients by appropriate use of grep()
. It happens that the CIDs all start with E followed by a 10 digit number so we can search for this pattern with a simple regular expression. Since we only need the QCs and patient data, the variable standards
is calculated only as a matter of completeness.
#separate out sample types standards <- grep("Blank|STD",quantifiers$sampleID) qc <- grep("C-", quantifiers$sampleID) #create a regular expression to identify samples (E followed by 10 digits) regexp<-"(^E)([[:digit:]]{10})" patients <-grep(pattern=regexp,quantifiers$sampleID) output.data <- quantifiers[c(qc,patients),]
Now we can prepare to write a dataframe corresponding to the required format of the output file. To do so, we'll need to find out how many rows we are writing and then prepare a vector of the same length repeating the name of the worksheet and testcode:
#prepare the final data num.rows <- length(output.data$sampleID) final.output.data <- data.frame(rep(worksheet,num.rows), output.data$sampleID, rep(test.code, num.rows), output.data$conc) names(final.output.data) <- c("worksheet","sample","test","conc")
Now we can replace all the NA values that replaced “No Peak” with the correct LoQ according to which analyte we are looking at.
#to put LOQs in, we need to convert to character #this assumes that all non numeric results are undetectable final.output.data$conc <- as.character(final.output.data$conc) final.output.data$conc[is.na(final.output.data$conc)] <- LoQ
Our final.output.data
dataframe looks like it behaved properly.
head(final.output.data,10)
## worksheet sample test conc ## 1 PAPI C-LY1LR TES 0.557 ## 2 PAPI C-LY1 TES 5.65 ## 3 PAPI C-LY2 TES 20.6 ## 4 PAPI C-LY3 TES 28.1 ## 5 PAPI C-PTES TES 0.737 ## 6 PAPI E1234083035 TES 1.04 ## 7 PAPI E1234109065 TES 14.1 ## 8 PAPI E1234086634 TES 19.2 ## 9 PAPI E1234107491 TES 13 ## 10 PAPI E1234114052 TES 18.6
And finally, we create directories to archive our data (if those directories do not exist) and write the files with an appropriate timestamp determined using Sys.time()
. Since colons (i.e : ) don't play nice in all operating systems as filenames, we can use gsub()
to get rid of them. We also pass along error messages or confirmation messages to the user as appropriate.
#If the data file happens to be empty because you selected the wrong file, abort if(nrow(final.output.data)==0){ tkmessageBox(message="Your flat file contained no patient data. Aborting file output") } else if (nrow(final.output.data)>0) { #create the output directory if it does not exist if(!dir.exists(file.path(flat.file.dir, "Processed"))){ dir.create(file.path(flat.file.dir, "Processed")) } if(!dir.exists(file.path(flat.file.dir, "Raw"))){ dir.create(file.path(flat.file.dir, "Raw")) } #create a ISO 8601 compliant timestamp - get rid of spaces and colons time.stamp <- gsub(":","", Sys.time(), fixed = TRUE) time.stamp <- gsub(" ","T", time.stamp, fixed = TRUE) #save a copy of the input file flat.file.copy.name <- paste(test.code,"_",time.stamp, "_Raw.txt", sep="") file.copy(flat.file.path, file.path(flat.file.dir,"Raw", flat.file.copy.name )) #write the final output file final.output.name <- paste(test.code,"_",time.stamp, ".txt", sep="") final.output.path <- file.path(flat.file.dir,"Processed" ,final.output.name) write.table(file = final.output.path, final.output.data, quote = FALSE, row.names = FALSE, col.names = FALSE, sep = ",") #check that the file was created as expected if(file.exists(final.output.path)){ tkmessageBox(message="Data successfully processed \n Check Processed directory") } else { tkmessageBox(message="Your file was not created. There was a problem") } }
Finally, we would wrap all of the directory–creation and file–operation in an if statement tied to the variable called problem
we created previously. You will see this in the final source–code linked below.
Now, you can easily modify this to deal with multiple anlytes that are always on the same run, such as Vitamin D2 and Vitamin D3. If you wanted to suppress results failing ion ratio criteria (which could be concentration–dependent of course) or if you had specimens unexpectedly low IS counts, you could easily censor them to prevent their upload and then review them manually. You could also append canned comments to your results with a dash between your result and the comment. In fact, you could theoretically develop very elaborate middleware for QC evaluation and interpretation. You could also use RMarkdown to generate PDF reports for the run which could include calibration curve plots, plots of quantifier results vs qualifier results, and results that fail various criteria.
You can download the source code and three example flat files here. Setting the source–code up as a “clickable” script is somewhat dependent on the operating system you are working on. Since most of you will be on a windows system you can follow this tutorial. You can also use a windows batch file to call your script.
Now that your file is generated, it is read to upload via ssh. This is usually performed manually but could be automated. Don't implement this code into routine use unless you know what you are doing and you have tested it extensively. By using and/or modifying it, you become entirely responsible for its correct operation. Excel is like a butter knife and R is like Swiss Army Knife. You must be careful with it because…
From everyone who has been given much, much will be demanded; and from the one who has been entrusted with much, much more will be asked.
Luke 12:48
]]>The lubridate package makes this a very easy thing to do. Suppose the first date in your series is 21-May-2015 and the last date is 19-Aug-2015.
library(lubridate) startDate <- dmy("21-May-2015") endDate <- dmy("19-Aug-2015")
Now build a sequence between the dates:
myDates <-seq(from = startDate, to = endDate, by = "days") head(myDates)
## [1] "2015-05-21 UTC" "2015-05-22 UTC" "2015-05-23 UTC" "2015-05-24 UTC" ## [5] "2015-05-25 UTC" "2015-05-26 UTC"
The function wday()
tells you which weekday a date corresponds to with Sunday being 1, Monday being 2 etc.
wday(startDate)
## [1] 5
This means that 2015-05-21 was a Thursday. To get the abbreviation, you can enter:
wday(startDate, label = TRUE)
## [1] Thurs ## Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat
and to get the full name of the day:
wday(startDate, label = TRUE, abbr = FALSE)
## [1] Thursday ## 7 Levels: Sunday < Monday < Tuesday < Wednesday < Thursday < ... < Saturday
Leap years are accounted for:
wday(dmy("29-Feb-1504"), label = TRUE, abbr = FALSE)
## [1] Monday ## 7 Levels: Sunday < Monday < Tuesday < Wednesday < Thursday < ... < Saturday
So, we can use this as follows to find the Mondays:
which(wday(myDates)==2)
## [1] 5 12 19 26 33 40 47 54 61 68 75 82 89
So the whole code to count them is:
startDate <- dmy("21-May-2015") endDate <- dmy("19-Aug-2015") myDates <-seq(from = startDate, to = endDate, by = "days") length(which(wday(myDates)==2))
## [1] 13
I was born on August 04, 1971. This was a Wednesday. How many Wednesdays since I was born?
startDate <- dmy("04-Aug-1971") endDate <- dmy("25-Nov-2015") myDates <-seq(from = startDate, to = endDate, by = "days") length(which(wday(myDates, label = TRUE)=="Wed"))
## [1] 2313
Which means, today I am 2312 weeks old today! Hurray. This is not a typo. The time interval is flanked by Wednesdays so there is one more Wednesday than the number of weeks in the interval. I thank my first–year calculus prof for beating this into me with reference to Simpson's Rule numerical integration.
Hope that comes in handy.
-Dan
I was honoured by a site visit by Drs. Yeo-Min Yun and Junghan Song of the Korean Society for Clinical Chemistry a few weeks ago. As both professors are on the organizing committee of the Cherry Blossom Symposium for Lab Automation in Seoul in Spring 2016, their primary motivation for visiting was to discuss mass spectrometry sample prep automation but later we got on to the topic of automated reporting for quality assurance schemes.
Naturally, I was promoting R, R-Markdown and knitr as a good pipeline for automated Quality Assurance (QA) report.
This brought to mind Youden Plots which are used by DGKL in their reports. I like DGKL reports for three reasons:
They are accuracy based against GC-MS when it comes to steroids.
I can see all the other LC-MS/MS methods immediately.
Youden plots look like a target and can be assessed rapidly.
The data for a Youden plot is generated by providing a number of laboratories aliquots from two separate unknown samples, which we will call A and B. Every lab analyzes both samples and a scatter plot of the A and B results are generated–the A results on the \(x\)–axis and the B results on the \(y\)–axis. Once this is completed, limits of acceptability are plotted and outliers can be identified.
In Youden's original formulation of the plot (see page 133-1 this online document) he required that the concentrations of the A and B samples be close to one another. As you might guess, in clinical medicine, this is not all that useful because we often want to test more than one part of the analytical range in an external quality assurance (EQA) scheme. One workaround for this is the make a Youden plot of the standard normal variates for the A and B samples, that is to plot \(z_b = \frac{b_i-\bar{b}} {\sigma_b}\) vs \(z_a = \frac{a_i-\bar{a}} {\sigma_a}\), where \(a_i\) and \(b_i\) are the individual values of the A and B samples from the \(i\) labs. This has the disadvantage of representing the results in a manner that is not easily assessed from a clinical perspective.
While there are published approaches to coping with this problem, these are out of scope here but I will show you a couple of other ways I have seen Youden plots represented. If you want to see R code to generate the classic Youden Plot, it can be found in this this stackoverflow post and below.
Let's start by generating some data. For the sake of argument, let's say we are looking at testosterone results in males and measured in nmol/L. Suppose that the A sample has a true concentration of 5.3 nmol/L and the B sample has a true concentration of 16.2 nmol/L. Let's also assume that they are all performed by the same analytical method. If you have looked at EQA reports, you will know that a scatter plot of results for the A and B samples does not typically look like this.
The (mock) data abaove are bivariate Gaussian and uncorrelated. In reality we often see something that looks a little more like this:
That is, the A and B values are usually correlated.
The most common manner in which you will see a Youden plot prepared is just a box with mean \(\pm\) 2SD and \(\pm\) 3SD limits.
plot(A,B, xlim = c(0,10), ylim = c(0,30), pch=19, col="#00000080") grid() A.mu <- mean(A) A.sd <- sd(A) B.mu <- mean(B) B.sd <- sd(B) #draw a box around the 2SD limit rect(xleft = A.mu - 2*A.sd, ybottom = B.mu - 2*B.sd, xright = A.mu + 2*A.sd, ytop = B.mu + 2*B.sd, lwd = 2, border = "orange") #draw a box around the 3SD limit rect(xleft = A.mu - 3*A.sd, ybottom = B.mu - 3*B.sd, xright = A.mu + 3*A.sd, ytop = B.mu + 3*B.sd, lwd = 2, border = "red") #draw a diagonal line - which is unnecessary but you will see people do it lines(c(A.mu - 3*A.sd, A.mu + 3*A.sd),c(B.mu - 3*B.sd, B.mu + 3*B.sd)) #draw horizontal line lines(c(A.mu - 3*A.sd, A.mu + 3*A.sd), c(B.mu, B.mu)) #draw vertical line lines(c(A.mu, A.mu), c(B.mu - 3*B.sd, B.mu + 3*B.sd)) #add a legend legend("topleft", c("2SD limit","3SD limit"), col=c("orange","red"), lty=c(1,1))
Obviously, if you prefer, you could prepare this Youden plot in a non-parametric fashion by plotting the medians and the non-parametrically calculated 1st, 2.5th, 97.5th, and 99th percentiles. In this case, the code would be:
plot(A,B, xlim = c(0,10), ylim = c(0,30), pch=19, col="#00000080") grid() A.med <- median(A) A.quants <- quantile(A, probs=c(0.01,0.025,0.975,0.99)) B.med <- median(B) B.quants <- quantile(B, probs=c(0.01,0.025,0.975,0.99)) #draw a box around the central 95% limit rect(xleft = A.quants[2], ybottom = B.quants[2], xright = A.quants[3], ytop = B.quants[3], lwd = 2, border = "orange") #draw a box around the central 99% limit rect(xleft = A.quants[1], ybottom = B.quants[1], xright = A.quants[4], ytop = B.quants[4], lwd = 2, border = "red") #draw a vertical line lines(c(A.quants[1],A.quants[4]),c(B.med,B.med)) #draw vertical line lines(c(A.med,A.med),c(B.quants[1],B.quants[4])) legend("topleft", c("Central 95%","Central 99%"), col=c("orange","red"), lty=c(1,1))
Note that if you increase the number of points, this non-parametric plot will not quite converge to look like the parametric one shown above because \(\mu \pm 2\sigma\) actually encompases 95.45% of the data in a univariate normal distribution, and \(\mu \pm 3\sigma\) actually encompases 99.73% of the data.
Be ye not deceived. Even with the non-parametric approach or a parametric approach with the correct \(z\)-scores, the orange (“Central 95%” or “2SD”) boxes shown above do not house 95% of the data and the red (“Central 99%” or “3SD”) boxes do not house 99% of the data. You can see this pretty easily if you consider the case of uncorrelated data. Let's take 100000 random pairs of uncorrelated Gaussian data with \(\mu = 10\) and \(\sigma = 1\).
Five percent of data points are excluded by the vertical orange lines shown below at the \(\mu_A \pm 1.96 \sigma_A\) and 5% of data are excluded by the horizontal orange lines positioned at \(\mu_B \pm 1.96 \sigma_B\).
Points will fall into the one of the 4 areas shaded yellow 0.95 x 0.025 or 2.375 % of the time and points will fall into one of the 4 areas shaded purple 0.025 x 0.025 or 0.0625 % of the time. This means that the “2SD” box actually encloses 100 – 4×2.375 – 4×0.0625 % = 90.25 % of the data.
Much more directly, the probability of both A and B falling inside the center square is 0.95×0.95 = 0.9025 = 90.25%.
You can do a random simulation to prove this to yourself:
#generate the data, n=10000 A <- rnorm(10^5,10,1) B <- rnorm(10^5,10,1) # convert results to z-scores scale.df <- data.frame(scA = scale(A), scB = scale(B)) #calculate how many samples are inside the centre box nrow(subset(scale.df, abs(scA)<1.96 & abs(scB)<1.96))
## [1] 90245
This is pretty darn close to the 90.25% we were expecting.
The rectangular plot shown works (with caveats described) but there is something slightly undesirable about it because a point could be off in the corner, far away from the other data, but still inside the 3SD box. It seems much preferable to encircle the data with an ellipse. Fortunately, there is a built in function to achieve this in the car
package which makes the code is very simple. The other nice thing is that the ellipses are actually calculated to house 95% and 99% of the data respectively.
library(car) dataEllipse(A, B, levels=c(0.95, 0.99), fill = FALSE, xlim = c(0,10), ylim = c(0,30), pch = 19, col=c("#00000080", "red"), center.pch = FALSE)
To generate a two–colour equivalent to what we have above we draw the Youden plot in two stages.
dataEllipse(A, B, levels = 0.95, fill = FALSE, xlim = c(0,10), ylim = c(0,30), pch = 19, col = c("#00000080", "orange"), center.pch = FALSE) dataEllipse(A, B, levels = 0.99, fill = FALSE, col = c(NA, "red"), center.pch = FALSE, plot.points = FALSE) legend("topleft", c("Central 95%","Central 99%"), col = c("orange","red"), lty=c(1,1))
Now we might want to add the horizontal, vertical lines.
#store the points of the outer ellipse in a matrix outer.ellipse <- dataEllipse(A, B, levels = 0.99, xlim = c(0,10), ylim = c(0,30), pch = 19, col = c("#00000080", "red"), draw = TRUE, center.pch = FALSE) #plot the innter ellipse dataEllipse(A, B, levels = 0.95, fill = FALSE, xlim = c(0,10), ylim = c(0,30), pch = 19, col = c("#00000080", "orange"), center.pch = FALSE, plot.points = FALSE, add = TRUE) #find the value of x that is closest to the mean value of A vert.index <- which.min(abs(A.mu-outer.ellipse[,1])) #calculate the vertical distance to centre vert.dist <- outer.ellipse[,2][vert.index] - B.mu #draw the line one end of ellipse to the other lines(c(A.mu, A.mu), c(outer.ellipse[,2][vert.index], outer.ellipse[,2][vert.index] - 2*vert.dist)) #find the value of y that is closest to the mean valye of B horiz.index <- which.min(abs(B.mu-outer.ellipse[,2])) #calculate the horizonal distance to centre horiz.dist <- outer.ellipse[,1][horiz.index] - A.mu #draw the line one end of ellipse to the other lines(c(outer.ellipse[,1][horiz.index], outer.ellipse[,1][horiz.index] - 2*horiz.dist), c(B.mu,B.mu)) #add a legend legend("topleft", c("Central 95%","Central 99%"), col=c("orange","red"), lty=c(1,1))
And if you wanted a little more groove you can add shading.
dataEllipse(A, B, levels = 0.99, xlim = c(0,10), ylim = c(0,30), pch = 19, col = c("#00000080", "red"), center.pch = FALSE, plot.points = TRUE, fill = TRUE, fill.alpha = 0.1) dataEllipse(A, B, levels=0.95 ,xlim = c(0,10), ylim = c(0,30), pch = 19, col="orange", center.pch = FALSE, plot.points = FALSE, add = TRUE, fill = TRUE, fill.alpha = 0.3) lines(c(A.mu, A.mu), c(outer.ellipse[,2][vert.index], outer.ellipse[,2][vert.index] - 2*vert.dist), col = "blue") lines(c(outer.ellipse[,1][horiz.index], outer.ellipse[,1][horiz.index] - 2*horiz.dist), c(B.mu,B.mu), col = "blue") legend("topleft", c("Central 95%","Central 99%"), col=c("orange","red"), lty=c(1,1))
We can also fold all of this into a function:
youden <- function(A,B,shape){ A.mu <- mean(A) A.sd <- sd(A) B.mu <- mean(B) B.sd <- sd(B) plot(A,B, pch=19, col = "#00000080", xlim = c(A.mu - 5*A.sd,A.mu + 5*A.sd), ylim = c(B.mu - 5*B.sd,B.mu + 5*B.sd)) grid() if (missing(shape)){ shape <- "ellipse" } if (shape == "rectangle"){ rect(xleft = A.mu - 2*A.sd, ybottom = B.mu - 2*B.sd, xright = A.mu + 2*A.sd, ytop = B.mu + 2*B.sd, lwd = 2, border = "orange") rect(xleft = A.mu - 3*A.sd, ybottom = B.mu - 3*B.sd, xright = A.mu + 3*A.sd, ytop = B.mu + 3*B.sd, lwd = 2, border = "red") lines(c(A.mu - 3*A.sd, A.mu + 3*A.sd),c(B.mu - 3*B.sd, B.mu + 3*B.sd)) lines(c(A.mu - 3*A.sd, A.mu + 3*A.sd), c(B.mu, B.mu)) lines(c(A.mu, A.mu), c(B.mu - 3*B.sd, B.mu + 3*B.sd)) legend("topleft", c("2SD limit","3SD limit"), col=c("orange","red"), lty=c(1,1)) } else if (shape=="ellipse") { outer.ellipse <- dataEllipse(A, B, levels = 0.99, pch = 19, col=c("#00000080", "red"), draw = TRUE, center.pch = FALSE, plot.points = FALSE) dataEllipse(A, B, levels = 0.95, fill = FALSE, pch = 19, col=c("#00000080", "orange"), center.pch = FALSE, plot.points = FALSE, add = TRUE) vert.index <- which.min(abs(A.mu-outer.ellipse[,1])) vert.dist <- outer.ellipse[,2][vert.index] - B.mu lines(c(A.mu, A.mu), c(outer.ellipse[,2][vert.index], outer.ellipse[,2][vert.index] - 2*vert.dist)) horiz.index <- which.min(abs(B.mu-outer.ellipse[,2])) horiz.dist <- outer.ellipse[,1][horiz.index] - A.mu lines(c(outer.ellipse[,1][horiz.index], outer.ellipse[,1][horiz.index] - 2*horiz.dist), c(B.mu,B.mu)) legend("topleft", c("Central 95%","Central 99%"), col=c("orange","red"), lty=c(1,1)) } } #use the function par(mfrow=c(1,2)) youden(A,B, shape = "rectangle") youden(A,B, shape = "ellipse")
If the data happens to be uncorrelated, and has identical average A and B values, the elliptical approach will generate a (nearly) circular Youden plot according to the original description. The youden.classic()
function code shown below is borrowed from the stackoverflow post mentioned above.
youden.classic <- function(A, B){ plot(A,B,asp = 1, xlab = "A", ylab = "B", pch=".") mB <- median(B) mA <- median(A) abline(h = mB, v = mA) curve(x-(mA-mB),add=TRUE) d <- mean(A-B) d_prime <- A-B-d r <- 2.45*mean(abs(d_prime))*sqrt(pi)/2 t <- seq(0,2*pi,by=0.01) x <- r*cos(t)+mA y <- r*sin(t)+mB lines(x,y) } #generate 10000 pairs of bivariate data with a mean of 10 for both A and B and 15% CV A <- rnorm(10000,10,1.5) B <- rnorm(10000,10,1.5) youden.classic(A,B) #overlay ellipse dataEllipse(A, B, levels = 0.95, fill = TRUE, fill.alpha = 0.3, col="orange", center.pch = FALSE, plot.points = FALSE, add = TRUE)
There you have it. With a Youden Plot it is easy to separate the sheep from the goats. There are lots of ways that you can dress up your plot to suit your needs. Of course, this could be embedded into an automated EQA report generated with R, Rmarkdown and knitr.
I hope that was helpful.
-Dan
]]>In this post we will be discussing how to perform Passing Bablok and Deming regression in R. Those who work in Clinical Chemistry know that these two approaches are required by the journals in the field. The idiosyncratic affection for these two forms of regression appears to be historical but this is something unlikely to change in my lifetime–hence the need to cover it here.
Along the way, we shall touch on the ways in which Deming and Passing Bablok differ from ordinary least squares (OLS) and from one another.
Let's start by making some heteroscedastic random data that we can use for regression. We will use the command set.seed()
to begin with because by this means, the reader can generate the same random data as the post. This function takes any number you wish as its argument, but if you set the same seed, you will get the same random numbers. We will generate 100 random \(x\) values in the uniform distribution and then an accompanying 100 random \(y\) values with proportional bias, constant bias and random noise that increases with \(x\). I have added a bit of non–linearity because we do see this a fair bit in our work.
set.seed(20) x <- runif(100,0,100) y <- 1.10*x - 0.001*x^2 + rnorm(100,0,1)*(2 + 0.05*x) + 15
The constants I chose are arbitrary. I chose them to produce something resembling a comparison of, say, two automated immunoassays.
Let's quickly produce a scatter plot to see what our data looks like:
plot(x,y, main = "Regression Comparison", xlab = "Current Method", ylab = "New Method")
OLS regression minimizes the sum of squared residuals. In the case of OLS, the residual of a point is defined as the vertical distance from that point to the regression line. The regression line is chosen so that the sum of the squares of the residuals in minimal.
OLS regression assumes that there is no error in the \(x\)–axis values and that there is no heteroscedasticity, that is, the scatter of \(y\) is constant. Neither of these assumptions is true in the case of bioanaytical method comparisons. In contrast, for calibration curves in mass–spectrometry, a linear response is plotted as a function of pre–defined calibrator concentration. This means that the \(x\)–axis has very little error and so OLS regression is an appropriate choice (though I doubt that the assumption about homoscedasticity is generally met).
OLS is part of R's base package. We can find the OLS regression line using lm()
and we will store the results in the variable lin.reg
.
plot(x,y, main = "Regression Comparison", xlab = "Current Method", ylab = "New Method") lin.reg <- lm(y~x) abline(lin.reg, col="blue")
Just to demonstrate the point about residuals graphically, the following shows them in vertical red lines.
Deming regression differs from OLS regression in that it does not make the assumption that the \(x\) values are free of error. It (more or less) defines the residual as the perpendicular distance from a point to its fitted value on the regression line.
Deming regression does not come as part of R's base package but can be performed using the MethComp and mcr packages. In this case, we will use the latter. If not already installed, you must install the mcr package with install.packages("mcr")
.
Then to perform Deming regression, we will load the mcr library and execute the following using the mcreg()
command, storing the output in the variable dem.reg
.
library(mcr) dem.reg <- mcreg(x,y, method.reg = "Deming")
By performing the str()
command on dem.reg
, we can see that the regression parameters are stored in the slot @para
. Because the authors have used an S4 object as the output of their function, we don't address output as we would in lists (with a $
), but rather with an @
.
str(dem.reg)
## Formal class 'MCResultResampling' [package "mcr"] with 21 slots ## ..@ glob.coef : num [1:2] 15.58 1.04 ## ..@ glob.sigma : num [1:2] 0.8165 0.0147 ## ..@ xmean : num 46.8 ## ..@ nsamples : int 999 ## ..@ nnested : num 25 ## ..@ B0 : num [1:999] 15.9 15.4 16 16.1 15.6 ... ## ..@ B1 : num [1:999] 1.01 1.04 1.02 1.04 1.03 ... ## ..@ sigmaB0 : num [1:999] 0.794 0.766 0.846 0.815 0.737 ... ## ..@ sigmaB1 : num [1:999] 0.0141 0.0142 0.0155 0.0141 0.0135 ... ## ..@ MX : num [1:999] 46.8 45.9 45.4 48.9 45.5 ... ## ..@ bootcimeth : chr "quantile" ## ..@ rng.seed : num NA ## ..@ rng.kind : chr NA ## ..@ data :'data.frame': 100 obs. of 3 variables: ## .. ..$ sid: Factor w/ 100 levels "S1","S10","S100",..: 1 13 24 35 46 57 68 79 90 2 ... ## .. ..$ x : num [1:100] 87.8 76.9 27.9 52.9 96.3 ... ## .. ..$ y : num [1:100] 110.8 93.5 45.6 76.6 116.6 ... ## ..@ para : num [1:2, 1:4] 15.58 1.04 NA NA 14.45 ... ## .. ..- attr(*, "dimnames")=List of 2 ## .. .. ..$ : chr [1:2] "Intercept" "Slope" ## .. .. ..$ : chr [1:4] "EST" "SE" "LCI" "UCI" ## ..@ mnames : chr [1:2] "Method1" "Method2" ## ..@ regmeth : chr "Deming" ## ..@ cimeth : chr "bootstrap" ## ..@ error.ratio: num 1 ## ..@ alpha : num 0.05 ## ..@ weight : Named num [1:100] 1 1 1 1 1 1 1 1 1 1 ... ## .. ..- attr(*, "names")= chr [1:100] "S1" "S2" "S3" "S4" ...
dem.reg@para
## EST SE LCI UCI ## Intercept 15.57790 NA 14.446677 16.810321 ## Slope 1.03658 NA 1.006434 1.066066
The intercept and slope are stored in demreg@para[1]
and dem.reg@para[2]
respectively. Therefore, we can add the regression line as follows:
plot(x,y, main = "Regression Comparison", xlab = "Current Method", ylab = "New Method") abline(dem.reg@para[1:2], col = "blue")
To emphasize how the residuals are different from OLS we can plot them as before:
We present the figure above for instructional purposes only. The usual way to present a residuals plot is to show the same picture rotated until the line is horizontal–this is a slight simplification but is essentially what is happening:
It is important to mention that if one knows that the \(x\)–axis method is subject to a different amount of random analytical variability than the \(y\)–axis method, one should provide the ratio of the variances of the two methods to mcreg()
. In general, this requires us to have “CV” data from precision studies already available. Another approach is to perform every analysis in duplicate by both methods and use the data to estimate this ratio.
If the methods happen to have similar CVs throughout the analytical range, the default value of 1 is assumed. But suppose that the ratio of the CVs of the \(x\) axis method to the \(y\)–axis method was 1.2, we could provide this in the regression call by setting the error.ratio
parameter. The resulting regression parameters will be slightly different.
mcreg(x,y, method.reg = "Deming", error.ratio = 1.2)@para
## EST SE LCI UCI ## Intercept 15.534921 NA 14.39904 16.777065 ## Slope 1.037499 NA 1.00792 1.067316
In the case of heteroscedastic data, it would be customary to weight the regression which in the case of the mcr package is weighted as \(1/x^2\). This means that having 0's in your \(x\)–data will cause the calculation to “crump”. In any case, if we wanted weighted regression parameters we would make the call:
w.dem.reg <- mcreg(x,y, method.reg = "WDeming")
## The global.sigma is calculated with Linnet's method
w.dem.reg@para
## EST SE LCI UCI ## Intercept 13.788450 NA 12.858803 14.861006 ## Slope 1.088119 NA 1.058042 1.116879
And plotting both on the same figure:
plot(x,y, main = "Regression Comparison", xlab = "Current Method", ylab = "New Method") abline(dem.reg@para[1:2], col = "blue") abline(w.dem.reg@para[1:2], col = "green") legend("topleft", c("Deming","Weighted Deming"), lty=c(1,1), col = c("blue","green"))
Passing Bablok regression is not performed by the minimization of residuals. Rather, all possible pairs of \(x\)–\(y\) points are determined and slopes are calculated using each pair of points. Work–arounds are undertaken for pairs of points that generate infinite slopes and other peculiarities. In any case, the median of the \(\frac{N(N-1)}{2!}\) possible slopes becomes the final slope estimate and the corresponding intercept can be calculated. With regards to weighted Passing Bablok regression, I’d like to acknowledge commenter glen_b for bringing to my attention that there is a paradigm for calculating the weighted median of pairwise slopes. See the comment section for a discussion.
Passing Bablok regression takes a lot of computational time as the number of points grows, so expect some delays on data sets larger than \(N=100\) if you are using an ordinary computer. To get the Passing Bablok regression equation, we just change the method.reg
parameter:
PB.reg <- mcreg(x,y, method.reg = "PaBa") PB.reg@para
## EST SE LCI UCI ## Intercept 14.684463 NA 13.648554 16.495846 ## Slope 1.046021 NA 1.015893 1.075632
and the procedures to plot this regression are identical. The mcreg()
function does have an option for Passing Bablok regression on large data sets. See the instructions by typing help("mcreg")
in the R terminal.
As a consequence of the means by which the slope is determined, the Passing Bablok method is relatively resistant to the effect of outlier(s) as compared to OLS and Deming. To demonstrate this, we can add on outlier to some data scattered about the line \(y=x\) and show how all three methods are affected.
x <- 1:20 y <- c(1:19,10) + rnorm(20,0,0.5)
Because of this outlier, the OLS slope drops to 0.84, the Deming slope to 0.91, while the Passing Bablok is much better off at 0.99.
The code authors of the mcr package have created a feature such that if you put the regression model inside the plot function, you can quickly generate a figure for yourself that has all the required information on it. For example,
plot(PB.reg)
But this method of out–of–the–box figure is not very customizable and you may want it to appear differently for your publication. Never fear. There is a solution. The MCResult.plot()
function offers complete customization of the figure so that you can show it exactly as you wish for your publication.
MCResult.plot(PB.reg, equal.axis = TRUE, x.lab = "x method", y.lab = "y method", points.col = "#FF7F5060", points.pch = 19, ci.area = TRUE, ci.area.col = "#0000FF50", main = "My Passing Bablok Regression", sub = "", add.grid = FALSE, points.cex = 1)
In this example, I have created semi–transparent “darkorchid4” (hex = #68228B) points and a semi–transparent blue (hex = #0000FF) confidence band of the regression. Maybe darkorchid would not be my first choice for a publication after all, but it demonstrates the customization. Additionally, I have suppressed my least favourite features of the default plot method. Specifically, the sub=""
term removes the sentence at the bottom margin and the add.grid = FALSE
prevents the grid from being plotted. Enter help(MCResult.plot)
for the complete low–down on customization.
We have seen how to perform Deming and Passing Bablok regression in the R programming language and have touched on how the methods differ “under the hood”. We have used the mcr
to perform the regressions and have shown how you can beautify your plot.
The reader should have a look at the rlm()
function in the MASS
package and the rq()
function in the quantreg
package to see other robust (outlier–resistant) regression approaches. A good tutorial can be found here
I hope that makes it easy for you.
-Dan
May all your paths (and regressions) be straight:
Trust in the Lord with all your heart
and lean not on your own understanding;
in all your ways submit to him,
and he will make your paths straight.
Proverbs 3:5-6
]]>