How to gracefully select and apply the calibration function, possibly using ddply?

I measure many different chemical compounds, each of which has a different calibration curve using one instrument. I would like to apply the correct calibration curve based on the connection name to the raw data to the raw data from the tool. So, I start with a few calibration curves and a raw data data frame:

#generate the calibration curves x <- 1:10 calib.data.1 <- x+runif(10) lm.1 <- lm(calib.data.1~x) calib.data.2 <- 2*x+runif(10) lm.2 <- lm(calib.data.2~x) 

Raw data is as follows:

 compound <- factor(c("cpd1", "cpd2")) values <- runif(2) raw <- data.frame(compound, values) 

It seems that an elegant way to choose the right calibration curve will include ddply or the like. However, I cannot figure out how to do this without writing a function in the following lines:

 choose.calib <- function(raw, cpd) if(cpd=="cpd1"){ calib=coef(lm.1)[1]+val*coef(lm.2)[2] }else{ if(cpd=="cpd2"){ calib=coef(lm.2)[1]+val*coef(lm.2)[2] }else{ warning("no calib curve for compound")}} } 

Then I would do something like

 cal<-ddply(raw, .(compound), choose.calib) 

(which does not work anyway due to my inability to understand if-else, but I think I can solve it myself)

Is there a more vector way to do this?

+4
source share
2 answers

Alternatively, you can create a list object with your models, indexed by their composite type. For instance. something like this should work:

  calibList <- list() calibList$cpd1 <- lm.1 calibList$cpd2 <- lm.2 choose.calib <- function(cpd, calibList){ return(calibList[[cpd]]) } predict.calib <- function(raw, cpd, calibList){ predict(choose.calib(cpd, calibList), raw) } ddply(raw, predict.calib, cpd, calibList) 

Itโ€™s good to know the predict.lm() function, so you donโ€™t need to extract the coefficients in order to manually perform the prediction.

+1
source

One way that just jumps at me is to create data.frame coefficients containing multiple fields, something like [cpd, intercept, coef]

Then you can โ€œattachโ€ your data.frame coefficients to your original data.frame using merge() , then you will have your calibration coefficients in the same data frame.

Here is a simple example of using your data:

 x <- 1:10 calib.data.1 <- x+runif(10) lm.1 <- lm(calib.data.1~x) lm1coef <- data.frame(compound="cpd1", t(lm.1$coefficients)) names(lm1coef) <- c("compound","intercept","b1") calib.data.2 <- 2*x+runif(10) lm.2 <- lm(calib.data.2~x) lm2coef <- data.frame(compound="cpd2",t(lm.2$coefficients)) names(lm2coef) <- c("compound","intercept","b1") coefs <- rbind(lm1coef, lm2coef) compound <- factor(c("cpd1", "cpd2")) values <- runif(2) raw <- data.frame(compound, values) raw2 <- merge(raw, coefs) 

Obviously, you can make a bit that extracts the coefficients into a function. But that gives you the gist.

+3
source

Source: https://habr.com/ru/post/1379319/


All Articles