## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", message = FALSE)

## ----example-data-------------------------------------------------------------
library(prolfqua)

samples <- c("S1", "S2", "S3")
quant <- data.frame(
  protein_Id = rep(c("StdA", "StdB", "Target"), each = 3),
  sampleName = rep(samples, 3),
  raw.file = rep(paste0(samples, ".raw"), 3),
  condition = rep(c("Control", "Control", "Treatment"), 3),
  intensity = c(64, 128, 32, 256, 512, 128, 512, 1024, 512),
  nr_children = 1
)

cfg <- AnalysisConfiguration$new()
cfg$file_name <- "raw.file"
cfg$hierarchy <- list(protein_Id = "protein_Id")
cfg$factors <- list(condition = "condition")
cfg$set_response("intensity")
lfq <- LFQData$new(quant, cfg, setup = TRUE)

logged <- lfq$get_Transformer()$log2()$lfq
logged$response()
head(logged$data_long()[c("protein_Id", "sampleName", lfq$response(), logged$response())])

## ----internal-standards-------------------------------------------------------
reference_ids <- data.frame(protein_Id = c("StdA", "StdB"))
reference <- logged$get_subset(reference_ids)
calibrated_internal <- logged$get_Transformer()$center_to_reference(reference)$lfq

## ----external-calibrants------------------------------------------------------
external <- data.frame(
  sampleName = c("S3", "S1", "S2"),
  measured_intensity = c(64, 128, 256)
)
offsets <- setNames(log2(external$measured_intensity / 128), external$sampleName)
offsets

calibrated_external <- logged$get_Transformer()$subtract_sample_offsets(offsets)$lfq

## ----comparison---------------------------------------------------------------
target_values <- function(lfq) {
  rows <- lfq$data_long()
  target <- rows[rows$protein_Id == "Target", ]
  setNames(target[[lfq$response()]], target$sampleName)[samples]
}

knitr::kable(
  data.frame(
    Sample = samples,
    `Original log2` = unname(target_values(logged)),
    `Internal standards` = unname(target_values(calibrated_internal)),
    `External calibrant` = unname(target_values(calibrated_external)),
    check.names = FALSE
  ),
  caption = "Target log2 intensity before and after calibration."
)

## ----session_info-------------------------------------------------------------
sessionInfo()

