content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Create a table for simple main effects analysis #' #' Automatically generates an HTML table with the results of a simple main effects analysis. #' #' @param audioData A data.frame generated by the autoExtract() function. #' @param by A character vector indicating the name of the factors. Note: it requires two factors. #' @param measure Name of the dependent variable. #' @param nameMeasure Optional string to rename the dependent variable in the output table. If no value is provided, the original variable name is displayed. #' @param figureNumber Integer indicating the figure number, used to create the title for the table. Default corresponds to 1. #' @return HTML table showing simple main effects analysis results in APA formatting style. #' @examples #' tableSimpleMainEffects(testAudioData, by = c("Condition", "Dimension"), measure = "duration") #' #' @importFrom stats aov as.formula #' @importFrom phia testInteractions #' @importFrom stringr str_replace_all #' @importFrom kableExtra kable_classic footnote #' @importFrom knitr kable #' @export tableSimpleMainEffects <- function(audioData, by = c(), measure = "duration", nameMeasure = c(), figureNumber = 1){ by <- as.vector(by) if(!is.data.frame(audioData)) stop("audioData should be a data.frame produced by autoExtract") if(length(measure) != 1 && !measure %in% colnames(audioData)) { stop("measure should be present on audioData") } if(sum(!by %in% colnames(audioData)) > 0){ stop(paste(by[which(!by %in% colnames(audioData))], "not found in audioData")) } # If by does not have length equal to 2 throw error if(length(by) != 2){ stop("Incorrect Number of by elements. It should contain 2.") } if(!(all(apply(audioData[, tolower(colnames(audioData)) %in% tolower(by), drop = FALSE], 2, is.factor)) || all(apply(audioData[, tolower(colnames(audioData)) %in% tolower(by), drop = FALSE], 2, is.character)))){ stop("Variables selected using by are not factors") } if(length(by) == 0){ stop("No by values provided.") } if(!is.numeric(audioData[,measure])){ stop("Variables selected using measure is not numeric") } if(length(nameMeasure) == 0 || !is.character(nameMeasure)){ nameMeasure <- measure } # Generate formula formula = as.formula(paste(measure, "~", by[1], "*", by[2])) audioData[,by[1]] <- as.factor(audioData[,by[1]]) audioData[,by[2]] <- as.factor(audioData[,by[2]]) #Compute two way anova res.aov2 <- aov(formula, audioData) #Test interactions SimpleMainEffectsTable <- testInteractions(res.aov2, fixed = by[1], across = by[2]) #Name table columns namesColumns <- vector(mode = "character", length = length(unique(audioData[, by[2]])) - 1) for(i in 2:length(unique(audioData[, by[2]]))){ namesColumns[i - 1] <- paste0("Mean difference <br/>(", unique(audioData[, by[2]])[1], " - ", unique(audioData[, by[2]])[i], ")") } colnames(SimpleMainEffectsTable)[1:(length(unique(audioData[, by[2]])) - 1)] <- namesColumns #Fill table and rename remaining columns SimpleMainEffectsTable[,1:(length(unique(audioData[, by[2]])) - 1)] <- round(SimpleMainEffectsTable[,1:(length(unique(audioData[, by[2]])) - 1)], 2) colnames(SimpleMainEffectsTable)[(length(unique(audioData[, by[2]]))):ncol(SimpleMainEffectsTable)] <- c("df", "SS", "F", "p") SimpleMainEffectsTable <- cbind(rownames(SimpleMainEffectsTable), SimpleMainEffectsTable) colnames(SimpleMainEffectsTable)[1] <- by[1] rownames(SimpleMainEffectsTable) <- c() SimpleMainEffectsTable[,c("SS", "F")] <- round(SimpleMainEffectsTable[,c("SS", "F")],2) SimpleMainEffectsTable$p <- round(SimpleMainEffectsTable$p, 3) SimpleMainEffectsTable[nrow(SimpleMainEffectsTable),which(is.na(SimpleMainEffectsTable[nrow(SimpleMainEffectsTable),]))] <- " " descriptionTable2 <- SimpleMainEffectsTable[1:(nrow(SimpleMainEffectsTable)-1),] #Convert p values into star notation if(length(descriptionTable2[descriptionTable2$p < 0.05, "p"]) > 0) descriptionTable2[descriptionTable2$p < 0.05, "sig"] <- paste(descriptionTable2[descriptionTable2$p < 0.05, "p"], "(*)") if(length(descriptionTable2[descriptionTable2$p < 0.01, "p"]) > 0) descriptionTable2[descriptionTable2$p < 0.01, "sig"] <- paste(descriptionTable2[descriptionTable2$p < 0.01, "p"], "(**)") if(length(descriptionTable2[descriptionTable2$p < 0.001, "p"]) > 0) descriptionTable2[descriptionTable2$p < 0.001, "sig"] <- paste(descriptionTable2[descriptionTable2$p < 0.001, "p"], "(***)") if(length(descriptionTable2[descriptionTable2$p >= 0.05, "p"]) > 0) descriptionTable2[descriptionTable2$p >= 0.05, "sig"] <- paste(descriptionTable2[descriptionTable2$p >= 0.05, "p"], " ") SimpleMainEffectsTable[1:(nrow(SimpleMainEffectsTable)-1),]$p <- descriptionTable2$sig columnNames <- colnames(SimpleMainEffectsTable) rowNames <- SimpleMainEffectsTable[,1] SimpleMainEffectsTable <- data.frame(lapply(SimpleMainEffectsTable, function(x) str_replace_all(x, "0\\.", "."))) colnames(SimpleMainEffectsTable) <- columnNames SimpleMainEffectsTable[,1] <- rowNames #Convert table into kable extra descriptionTable <- kable_classic(kable( SimpleMainEffectsTable, format = "html", booktabs = TRUE, escape = FALSE, caption = paste0("Figure ", figureNumber, ". Simple Main effects for ", nameMeasure, " by ", paste(by[1], "and", by[2])) ), full_width = F, html_font = "Cambria") descriptionTable <- footnote(descriptionTable, general ="* p < .05, ** p < .01, *** p < .001", threeparttable = TRUE, footnote_as_chunk = TRUE) return(descriptionTable) }
/scratch/gouwar.j/cran-all/cranData/voiceR/R/tableSimpleMainEffects.R
#' Create a summary table #' #' Automatically generates HTML table with the main descriptive statistics (mean, standard deviation and number of data points) for each variable of the data set. Descriptive statistics can be conditioned by groups if grouping variables are defined. #' #' @param audioData A data.frame generated by the autoExtract() function. #' @param by A character vector indicating the name of the factor(s). #' @param measures A character vector indicating the name of the variables to be included in the table. #' @param nameMeasures Optional character vector indicating the names to be displayed for each of the different measures in the output table. If no value is provided, original variable names are displayed. #' @param figureNumber Integer indicating figure number, used to create the title for the table. Default corresponds to 1. #' @return HTML file summarizing the main descriptive statistics for each variable, conditioned by group(s) if one or more factors are provided. #' @examples #' tableSummary(testAudioData, by = c("Condition", "Dimension"), #' measures = c("duration", "voice_breaks_percent", "RMS_env", "mean_loudness", #' "mean_F0")) #' #' @importFrom stats sd as.formula aggregate na.pass #' @importFrom kableExtra kable_classic add_header_above footnote #' @importFrom knitr kable #' @export tableSummary <- function(audioData, by = c(), measures = c("duration", "voice_breaks_percent", "RMS_env", "mean_loudness", "mean_F0", "sd_F0", "mean_entropy", "mean_HNR"), nameMeasures = c(), figureNumber = 1){ if(!is.data.frame(audioData)) stop("audioData should be a data.frame produced by autoExtract") if(!all(measures %in% colnames(audioData))){ stop(paste(measures[which(!measures %in% colnames(audioData))], "not found in audioData")) } if(sum(!by %in% colnames(audioData)) > 0){ stop(paste(by[which(!by %in% colnames(audioData))], "not found in audioData")) } if(!(all(apply(audioData[, tolower(colnames(audioData)) %in% tolower(by), drop = FALSE], 2, is.factor)) || all(apply(audioData[, tolower(colnames(audioData)) %in% tolower(by), drop = FALSE], 2, is.character)))){ stop("Variables selected using by are not factors") } if(!all(apply(audioData[,tolower(colnames(audioData)) %in% tolower(measures), drop = FALSE], 2, is.numeric))){ stop("Variables selected using measures are not numeric") } #If no custom name provided for the measure, use the measure name if(length(nameMeasures) == 0){ nameMeasures <- measures } audioData <- audioData[,!(names(audioData) %in% "ID")] audioData <- audioData[,names(audioData) %in% by | names(audioData) %in% measures] #If no factors, just report means and standard deviations of audio measures, plus overall number of observations if(length(by) == 0){ numericColumns <- unlist(lapply(audioData, is.numeric)) descriptionTable <- apply(audioData[,numericColumns], 2,FUN = function(x) c(N = round(length(x), 0), M = round(mean(x, na.rm = TRUE), 2), SD = round(sd(x, na.rm = TRUE), 2) )) descriptionTable <- kable_classic(kable( descriptionTable, col.names = nameMeasures, format = "html", booktabs = TRUE, caption = paste0("Figure ", figureNumber, ". Means and Standard Deviations of Audio Measures") ), full_width = F, html_font = "Cambria") } #if factors are specified report means, audios and number of observations according to them else{ formula = as.formula(paste(". ~", ifelse(length(by) == 1, by, paste(by[1], "+", by[2])))) descriptionTable <- do.call(data.frame,(aggregate(formula, data = audioData, FUN = function(x) c(N = round(length(x), 0), M = round(mean(x, na.rm = TRUE), 2), SD = round(sd(x, na.rm = TRUE), 2) ), na.action = na.pass))) headerNames <- c(length(by), rep(3, length(measures))) names(headerNames) <- c(" ", nameMeasures) descriptionTable <- kable_classic(kable( descriptionTable, col.names = c(colnames(descriptionTable)[1:length(by)],rep(c("N", "M", "SD"), length(measures))), format = "html", booktabs = TRUE, caption = paste0("Figure ", figureNumber,". Means and Standard Deviations of Audio Measures by ", ifelse(length(by) == 1, by, paste(by[1], "and", by[2])) ) ), full_width = F, html_font = "Cambria") descriptionTable <- add_header_above(descriptionTable, headerNames, escape = FALSE, line_sep = 0) } #Convert table into kable extra format descriptionTable <- footnote(descriptionTable, general ="N, M and SD are used to represent number of data points, mean and standard deviation, respectively.", threeparttable = TRUE, footnote_as_chunk = TRUE) return(descriptionTable) }
/scratch/gouwar.j/cran-all/cranData/voiceR/R/tableSummary.R
#'Create a table for Tukey HSD test results #' #' Automatically generates an HTML table with the results of a Tukey HSD test. #' #' @param audioData A data.frame generated by the autoExtract() function. #' @param by A character vector indicating the name of the factor(s). #' @param measure Name of the dependent variable. #' @param nameMeasure Optional string to rename the dependent variable in the output table. If no value is provided, the original variable name is displayed. #' @param figureNumber Integer indicating the figure number, used to create the title for the table. Default corresponds to 1. #' @return HTML table showing Tukey HSD test results in APA formatting style. #' @examples #' tableTukey(testAudioData, by = "Condition", measure = "duration") #' #' @importFrom stats aov as.formula TukeyHSD #' @importFrom stringr str_replace str_split #' @importFrom kableExtra kable_classic footnote #' @importFrom knitr kable #' @export tableTukey <- function(audioData, by = c(), measure = "duration", nameMeasure = c(), figureNumber = 1){ by <- as.vector(by) if(!is.data.frame(audioData)) stop("audioData should be a data.frame produced by autoExtract") if(length(measure) != 1 && !measure %in% colnames(audioData)) { stop("measure should be present on audioData") } if(sum(!by %in% colnames(audioData)) > 0){ stop(paste(by[which(!by %in% colnames(audioData))], "not found in audioData")) } if(length(by) == 0){ stop("No by values provided.") } if(!(all(apply(audioData[, tolower(colnames(audioData)) %in% tolower(by), drop = FALSE], 2, is.factor)) || all(apply(audioData[, tolower(colnames(audioData)) %in% tolower(by), drop = FALSE], 2, is.character)))){ stop("Variables selected using by are not factors") } if(!is.numeric(audioData[,measure])){ stop("Variable selected using measure is not numeric") } #If no custom name provided for the measure, use the measure name if(length(nameMeasure) == 0 || !is.character(nameMeasure)){ nameMeasure <- measure } # Generate formula formula = as.formula(paste(measure, "~", by)) #Compute Tukey HSD test tukeyData <- TukeyHSD(aov(formula, data = audioData)) #Create data.frame from results tukeyData <- as.data.frame(tukeyData[[by]]) #Process names tukeyData$group1 <- trimws(str_split(rownames(tukeyData), "-", simplify = T)[,1]) tukeyData$group2 <- trimws(str_split(rownames(tukeyData), "-", simplify = T)[,2]) rownames(tukeyData) <- str_replace(rownames(tukeyData), "-", " and ") #Create empty data.frame for the final table descriptionTable <- as.data.frame(matrix(nrow = length(unique(audioData[,by])), ncol = length(unique(audioData[,by])))) colnames(descriptionTable) <- unique(audioData[,by]) rownames(descriptionTable) <- unique(audioData[,by]) descriptionTable[lower.tri(descriptionTable)] <- " " descriptionTable[row(descriptionTable) == col(descriptionTable)] <- "1" #Fill the empty data.frame for (i in 1:nrow(descriptionTable)) { for(j in which(is.na(descriptionTable[i,]))){ number <- tukeyData[tukeyData$group1 == rownames(descriptionTable)[i] & tukeyData$group2 == colnames(descriptionTable)[j] | tukeyData$group2 == rownames(descriptionTable)[i] & tukeyData$group1 == colnames(descriptionTable)[j],"diff"] number <- str_replace(round(number, 2), "0\\.", ".") if(tukeyData[tukeyData$group1 == rownames(descriptionTable)[i] & tukeyData$group2 == colnames(descriptionTable)[j] | tukeyData$group2 == rownames(descriptionTable)[i] & tukeyData$group1 == colnames(descriptionTable)[j],"p adj"] < 0.05) descriptionTable[i, j] <- paste(number, "(*)") if(tukeyData[tukeyData$group1 == rownames(descriptionTable)[i] & tukeyData$group2 == colnames(descriptionTable)[j] | tukeyData$group2 == rownames(descriptionTable)[i] & tukeyData$group1 == colnames(descriptionTable)[j] | tukeyData$group2 == rownames(descriptionTable)[i] & tukeyData$group1 == colnames(descriptionTable)[j],"p adj"] < 0.01) descriptionTable[i, j] <- paste(number, "(**)") if(tukeyData[tukeyData$group1 == rownames(descriptionTable)[i] & tukeyData$group2 == colnames(descriptionTable)[j] | tukeyData$group2 == rownames(descriptionTable)[i] & tukeyData$group1 == colnames(descriptionTable)[j] | tukeyData$group2 == rownames(descriptionTable)[i] & tukeyData$group1 == colnames(descriptionTable)[j],"p adj"] < 0.001) descriptionTable[i, j] <- paste(number, "(***)") if(tukeyData[tukeyData$group1 == rownames(descriptionTable)[i] & tukeyData$group2 == colnames(descriptionTable)[j] | tukeyData$group2 == rownames(descriptionTable)[i] & tukeyData$group1 == colnames(descriptionTable)[j],"p adj"] >= 0.05) descriptionTable[i, j] <- paste(number, " ") } } #Final postprocessing and conversion into kable extra format descriptionTable <- cbind(unique(audioData[,by]), descriptionTable) colnames(descriptionTable)[1] <- " " rownames(descriptionTable) <- c() descriptionTable <- kable_classic(kable( descriptionTable, format = "html", booktabs = TRUE, caption = paste0("Figure ", figureNumber, ". Posthoc comparisons using Tukey's HSD Test for ", nameMeasure, " by ", by[1]) ), full_width = T, html_font = "Cambria") descriptionTable <- footnote(descriptionTable, general ="Mean difference shown<br/>* p < .05, ** p < .01, *** p < .001", threeparttable = TRUE, footnote_as_chunk = TRUE, escape = FALSE) return(descriptionTable) }
/scratch/gouwar.j/cran-all/cranData/voiceR/R/tableTukey.R
#' voiceR test Audio Data #' #' #' A test audio features data.frame, obtained by using autoExtract() on #' the extended version of testAudioList, found #' <a href="https://osf.io/zt5h2/?view_only=348d1d172435449391e8d64547716477">here</a>. #' #' #' @name testAudioData #' @docType data #' @format `testAudioData` #' A data.frame containing 90 observations and 11 variables, which is the result of #' applying the autoExtract() function to the extended version of the data found #' on testAudioList. This data.frame contains several voice features for 90 audio #' files, which correspond to 15 English-speaking participants. #' Participants first completed a Baseline Voice Task in which they were #' instructed to read two predefined phrases ((1) Bar: "I go to the bar", #' (2) Beer: "I drink a beer") aloud in their normal (neutral) voice. #' Participants were then instructed to read the predefined phrases in either #' a happy or a sad voice. The experimenter requested #' each emotion one at a time and in a random sequence to counter-order effects. #' Participants were then asked to describe their experience of mimicking the #' stated phrases for each of the specified emotional states. #' Thus the data contains 6 observations per participant: two observations for #' the neutral state, two for the happy simulated state, and two for the sad #' simulated state. #' Below we also provide information about the columns this data.frame contains: #' \describe{ #' \item{ID}{Participant identifier} #' \item{Condition}{refers to the intention or emotional aspect that #' the speaker is conveying: Happy, or Sad. This component makes #' reference to the main point that we want to compare in our data; in the #' voiceR package the main comparison component is called Condition, because #' it usually refers to experimental conditions.} #' \item{Dimensions}{Phrase participants read: (1) Bar: "I go to the bar"; #' (2): Beer: "I drink a beer"} #' \item{duration}{Total duration in seconds.} #' \item{voice_breaks_percent}{Proportion of unvoiced frames.} #' \item{RMS_env}{Root mean square of the amplitude envelope.} #' \item{mean_loudness}{Average subjective loudness in sone.} #' \item{mean_F0}{Average fundamental frequency in Hertz.} #' \item{sd_F0}{Standard deviation of the fundamental frequency in Hertz.} #' \item{mean_entropy}{Average Wiener entropy. A value of 0 indicates a pure tone, while a value of 1 indicates white noise.} #' \item{mean_HNR}{Average Harmonics-to-Noise Ratio.} #' } #' @examples #' data(testAudioData) NULL
/scratch/gouwar.j/cran-all/cranData/voiceR/R/testAudioData.R
#' voiceR test Audio List #' #' #' An audio list containing recordings for ten English-speaking participants. #' Interested users can download an extended version of this data set #' <a href="https://osf.io/zt5h2/?view_only=348d1d172435449391e8d64547716477">here</a> #' Participants were seated with an experimenter in a sound-isolated room. #' All voice recordings were collected using a Blue Yeti Microphone. We used #' Audacity version 2.4.2 to record the audio files and saved all files using #' a 32-bit WAV format. #' Participants were instructed to read the phrase "I go to the bar" in either a happy #' or a sad voice. The experimenter requested #' each emotion one at a time and in random sequence to counter order effects. #' #' @name testAudioList #' @docType data #' @format `testAudioList` #' A list containing 20 Wave objects. Each Wave object has as name its file name. #' This file name contains three components separated by an underscore: #' \describe{ #' \item{First component}{combination of numbers and letters refers to the #' participant identifier, i.e., the ID component} #' \item{Second component}{refers to the intention or emotional aspect that #' the speaker is conveying: Happy, or Sad. This component makes #' reference to the main point that we want to compare in our data; in the #' voiceR package the main comparison component is called Condition, because #' it usually refers to experimental conditions.} #' \item{Third component}{provides additional information in the voiceR #' package. } #' } #' @examples #' data(testAudioList) NULL
/scratch/gouwar.j/cran-all/cranData/voiceR/R/testAudioList.R
#' Start voiceR Shiny App #' #' Launches the voiceR Shiny app, providing the opportunity to analyze multiple audio files via a graphical user interface (no-code interface). #' @return This function launches the voiceR Shiny app. #' @examples #' if(interactive()){ #' voiceRApp() #' } #' #' #' @importFrom shiny runApp withProgress incProgress downloadHandler reactiveValues reactive renderText observeEvent #' @importFrom shinyjs html hide show #' @importFrom shinyFiles getVolumes shinyDirChoose #' @importFrom stringr str_remove_all str_split str_detect str_extract str_replace #' @importFrom tuneR readMP3 readWave #' @importFrom parallel makeCluster detectCores stopCluster #' @importFrom doParallel registerDoParallel #' @importFrom soundgen analyze #' @importFrom seewave duration rms env zapsilw #' @importFrom DT renderDataTable #' @importFrom plotly ggplotly renderPlotly plot_ly layout subplot #' @importFrom ggplot2 ggplot_build ylim labs #' @importFrom ggthemes theme_fivethirtyeight #' @importFrom rmarkdown render html_document #' @export voiceRApp <- function() { #Get app directory for the shiny app appDir <- system.file("AppShiny", package = "voiceR") #If appDir is blank throw error if (appDir == "") { stop("Could not find shiny-app directory. Try re-installing `voiceR`.", call. = FALSE) } #run the shiny app runApp(appDir, display.mode = "normal") }
/scratch/gouwar.j/cran-all/cranData/voiceR/R/voiceRApp.R
--- title: "VoiceR Saved Report" output: html_document params: audioData: NA comparisons: NA normalPlots: NA includeDimensions: NA avoidNormalCheck: NA --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r message=FALSE, warning=FALSE, include=FALSE} createNormalityText <- function(audioData, measure, nameMeasure, includeDimensions = FALSE, avoidNormalCheck = FALSE, BoxCoxConstant = FALSE){ if(sum(!is.na(audioData[,measure])) < 3){ return("All values are NA.") } normalityData <- tableNormality(audioData, measure, includeDimensions = includeDimensions) if(is.character(normalityData)){ text <- normalityData } NOTnormal <- normalityData$pValue[1] < 0.05 if(min(normalityData$pValue)<0.05 & avoidNormalCheck){ text <- ifelse(nrow(normalityData) > 1, paste0("Box-Cox Procedure was used to transform ", nameMeasure, " to follow a more normal distribution. ", ifelse(BoxCoxConstant != FALSE, paste0("In order to apply Box-Cox transformation to ", nameMeasure, " a constat equal to ", BoxCoxConstant, " was added to it in order to make it positive."), "")), paste0(" Tukey Ladder of Powers was used to transform ", nameMeasure, " to follow a more normal distribution. ")) } else{ text <- "" } if(nrow(audioData) > 3){ if(NOTnormal){ text <- paste0(text, "A Shapiro-Wilk test showed a significant departure from normality for the ", nameMeasure, " measure, W(", normalityData$N[1], ") = ", normalityData$W[1], ", ", ifelse(normalityData$pValue[1] < 0.001, "p < .001", ifelse(normalityData$pValue[1] < 0.01, "p < .01", ifelse(normalityData$pValue[1] < 0.05, "p < .05", paste("p = ", round(normalityData$pValue[1], 2))))), ".") if("Condition" %in% colnames(audioData)){ if(any(normalityData[-1,]$pValue > 0.05)){ text2 <- "Although, a Shapiro-Wilk test did not show a significant departure from normality " for (i in (which(normalityData[-1,]$pValue > 0.05) + 1)) { text2 <- paste0(text2,"for ", normalityData$Condition[i], " condition", ", W(", normalityData$N[i], ") = ", normalityData$W[i], ", ", ifelse(normalityData$pValue[i] < 0.001, "p < .001", ifelse(normalityData$pValue[i] < 0.01, "p < .01", ifelse(normalityData$pValue[i] < 0.05, "p < .05", paste("p = ", round(normalityData$pValue[i],2)))))) if(length(which(normalityData[-1,]$pValue > 0.05) + 1) > 1){ if(i >= (which(normalityData[-1,]$pValue > 0.05) + 1)[1] & i < (which(normalityData[-1,]$pValue > 0.05) + 1)[length(which(normalityData[-1,]$pValue > 0.05) + 1) - 1]){ text2 <- paste0(text2, "; ") } else if(i == (which(normalityData[-1,]$pValue > 0.05) + 1)[length(which(normalityData[-1,]$pValue > 0.05) + 1)-1]){ text2 <- paste0(text2, " and ") } } } text <- paste0(text, " ", text2, ".") } } }else{ text <- paste0(text, "A Shapiro-Wilk test did not show a significant departure from normality for the ", nameMeasure, " measure, W(", normalityData$N[1], ") = ", normalityData$W[1], ", ", ifelse(normalityData$pValue[1] < 0.001, "p < .001", ifelse(normalityData$pValue[1] < 0.01, "p < .01", ifelse(normalityData$pValue[1] < 0.05, "p < .05", paste("p = ", round(normalityData$pValue[1], 2))))), ".") if("Condition" %in% colnames(audioData)){ if(any(normalityData[-1,]$pValue < 0.05)){ text2 <- "Although, a Shapiro-Wilk test showed a significant departure from normality " for (i in (which(normalityData[-1,]$pValue < 0.05) + 1)) { text2 <- paste0(text2,"for ", normalityData$Condition[i], " condition", ", W(", normalityData$N[i], ") = ", normalityData$W[i], ", ", ifelse(normalityData$pValue[i] < 0.001, "p < .001", ifelse(normalityData$pValue[i] < 0.01, "p < .01", ifelse(normalityData$pValue[i] < 0.05, "p < .05", paste("p = ", round(normalityData$pValue[i], 2)))))) if(length(which(normalityData[-1,]$pValue < 0.05) + 1) > 1){ if(i >= (which(normalityData[-1,]$pValue > 0.05) + 1)[1] & i < (which(normalityData[-1,]$pValue < 0.05) + 1)[length(which(normalityData[-1,]$pValue < 0.05) + 1)-1]){ text2 <- paste0(text2, "; ") } else if(i == (which(normalityData[-1,]$pValue < 0.05) + 1)[length(which(normalityData[-1,]$pValue < 0.05) + 1)-1]){ text2 <- paste0(text2, " and ") } } } text <- paste0(text, " ", text2, ".") } } } } return(text) } ``` ```{r message=FALSE, warning=FALSE, include=FALSE} createComparisonText <- function(audioData, measure, nameMeasure, includeDimensions = FALSE, avoidNormalCheck = FALSE){ if(sum(!is.na(audioData[,measure])) < 3){ return("All values are NA.") } normalityData <- tableNormality(audioData, measure, includeDimensions) if("Condition" %in% colnames(audioData) & !includeDimensions){ if(length(unique(audioData$Condition)) > 2){ if(min(normalityData$pValue)<0.05 & !avoidNormalCheck){ kruskalTestData <- kruskal.test(as.formula(paste0(measure, "~", "Condition")), audioData) audioData$VarRank <- rank(audioData[,measure], ties.method = "average") dunnData <- FSA::dunnTest(as.formula(as.formula(paste0(measure, "~", "Condition"))), data = audioData) dunnData$res$Comparison <- stringr::str_replace(dunnData$res$Comparison, "-", "and") text2 <- "" for(conditionNumber in 1:length(unique(audioData$Condition))){ text2 <- paste0(text2, round(mean(audioData[audioData$Condition == unique(audioData$Condition)[conditionNumber],"VarRank"]),2), " for ", unique(audioData$Condition)[conditionNumber]) if(length(unique(audioData$Condition)) > 1 & conditionNumber < length(unique(audioData$Condition)) - 1){ text2 <- paste0(text2, ", ") } else if(length(unique(audioData$Condition)) > 1 & conditionNumber == length(unique(audioData$Condition)) - 1){ text2 <- paste0(text2, " and ") } else{ text2 <- paste0(text2, ".") } } if(kruskalTestData$p.value < 0.05){ text <- paste0("A Kruskal-Wallis H test showed that there was a statistically significant difference in audios ", nameMeasure, " between the different conditions, X²(", round(kruskalTestData$parameter, 2), ") = ", round(kruskalTestData$statistic, 2), ", ", ifelse(kruskalTestData$p.value < 0.001, "p < .001", ifelse(kruskalTestData$p.value < 0.01, "p < .01", ifelse(kruskalTestData$p.value < 0.05, "p < .05", paste("p = ", round(kruskalTestData$p.value, 2))))), ", with a mean rank ", nameMeasure, " of ", text2) if(any(dunnData$res$P.adj < 0.05)){ text <- paste0(text, " Post hoc comparisons using the Dunn's Test showed significant differences in ", nameMeasure, "'s mean rank between ") for (i in 1:nrow(dunnData$res[dunnData$res$P.adj < 0.05,])) { if(nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) > 1 & i < nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) - 1){ text <- paste0(text, dunnData$res[dunnData$res$P.adj < 0.05,]$Comparison[i], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i], 2))))), ")" ,", ") } else if(nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) > 1 & i == nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) - 1){ text <- paste0(text, dunnData$res[dunnData$res$P.adj < 0.05,]$Comparison[i], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i], 2))))), ") " , " and ") } else{ text <- paste0(text, dunnData$res[dunnData$res$P.adj < 0.05,]$Comparison[i], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.05, "p < .05", round(paste("p = ", dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i], 2))))), ")" , ".") } } if(any(dunnData$res$P.adj > 0.05)){ text <- paste0(text, " However, no significant differences were found between ") for (i in 1:nrow(dunnData$res[dunnData$res$P.adj > 0.05,])) { if(nrow(dunnData$res[dunnData$res$P.adj > 0.05,]) > 1 & i < nrow(dunnData$res[dunnData$res$P.adj > 0.05,]) - 1){ text <- paste0(text, dunnData$res[dunnData$res$P.adj > 0.05,]$Comparison[i], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i], 2))))) , ")" ,", ") } else if(nrow(dunnData$res[dunnData$res$P.adj > 0.05,]) > 1 & i == nrow(dunnData$res[dunnData$res$P.adj > 0.05,]) - 1){ text <- paste0(text, dunnData$res[dunnData$res$P.adj > 0.05,]$Comparison[i], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i], 2))))), ") " , "and ") } else{ text <- paste0(text, dunnData$res[dunnData$res$P.adj > 0.05,]$Comparison[i], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[i], 2))))), ")" , " conditions.") } } } } } else{ text <- paste0("A Kruskal-Wallis H test did not show that there was a statistically significant difference in audios ", nameMeasure, " between the different conditions, X²(", round(kruskalTestData$parameter, 2), ") = ", round(kruskalTestData$statistic, 2), ", ", ifelse(kruskalTestData$p.value < 0.001, "p < .001", ifelse(kruskalTestData$p.value < 0.01, "p < .01", ifelse(kruskalTestData$p.value < 0.05, "p < .05", paste("p = ", round(kruskalTestData$p.value, 2))))), ", with a mean rank ", nameMeasure, " of ", text2) if(any(dunnData$res$P.adj < 0.05)){ text <- paste0(text, " However, significant differences were found between ") for (i in 1:nrow(dunnData$res[dunnData$res$P.adj < 0.05,])) { if(nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) > 1 & i < nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) - 1){ text <- paste0(text, dunnData$res[dunnData$res$P.adj < 0.05,]$Comparison[i], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i], 2))))), ")" ,", ") } else if(nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) > 1 & i == nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) - 1){ text <- paste0(text, dunnData$res[dunnData$res$P.adj < 0.05,]$Comparison[i], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i], 2))))), ") " , " and ") } else{ text <- paste0(text, dunnData$res[dunnData$res$P.adj < 0.05,]$Comparison[i], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[i], 2))))), ")" , ".") } } } } } else{ AnovaTestData <- summary(aov(as.formula(paste0(measure, "~", "Condition")), audioData)) tukeyData <- TukeyHSD(aov(as.formula(paste0(measure, "~", "Condition")), data = audioData)) tukeyData <- as.data.frame(tukeyData$Condition) tukeyData$group1 <- stringr::str_split(rownames(tukeyData), "-", simplify = T)[,1] tukeyData$group2 <- stringr::str_split(rownames(tukeyData), "-", simplify = T)[,2] rownames(tukeyData) <- stringr::str_replace(rownames(tukeyData), "-", " and ") if(AnovaTestData[[1]]["Condition",]$`Pr(>F)` < 0.05){ text <- paste0("An analysis of variance (ANOVA) on ", nameMeasure, " yielded significant variation among conditions, F(", AnovaTestData[[1]]["Condition",]$Df, ", ", AnovaTestData[[1]]["Residuals",]$Df, ") = ", round(AnovaTestData[[1]]["Condition",]$`F value`, 2), ", ", ifelse(AnovaTestData[[1]]["Condition",]$`Pr(>F)` < 0.001, "p < .001", ifelse(AnovaTestData[[1]]["Condition",]$`Pr(>F)` < 0.01, "p < .01", ifelse(AnovaTestData[[1]]["Condition",]$`Pr(>F)` < 0.05, "p < .05", paste("p = ", round(AnovaTestData[[1]]["Condition",]$`Pr(>F)`, 2))))), ".") if(any(tukeyData$`p adj` < 0.05)){ for (i in 1:nrow(tukeyData)) { tukeyData$mean1[i] <- mean(audioData[audioData$Condition == tukeyData$group1[i], measure], na.rm = TRUE) tukeyData$mean2[i] <- mean(audioData[audioData$Condition == tukeyData$group2[i], measure], na.rm = TRUE) tukeyData$comparison[i] <- ifelse(tukeyData$mean1[i] > tukeyData$mean2[i], "greater", ifelse(tukeyData$mean1[i] == tukeyData$mean2[i], "equal", "smaller")) tukeyData$sd1[i] <- sd(audioData[audioData$Condition == tukeyData$group1[i], measure], na.rm = TRUE) tukeyData$sd2[i] <- sd(audioData[audioData$Condition == tukeyData$group2[i], measure], na.rm = TRUE) } text <- paste0(text, " Post hoc comparisons using the Tukey HSD Test indicated that ") for (i in 1:nrow(tukeyData[tukeyData$`p adj` < 0.05,])) { if(nrow(tukeyData[tukeyData$`p adj` < 0.05,]) > 1 & i < nrow(tukeyData[tukeyData$`p adj` < 0.05,]) - 1){ text <- paste0(text, " ", nameMeasure, " of the audios in the ", tukeyData[tukeyData$`p adj` < 0.05,]$group1[i], " condition", " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean1[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd1[i], 2), ")", " were significantly ", tukeyData[tukeyData$`p adj` < 0.05,]$comparison[i], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i], 2))))), ")", " than in the ", tukeyData$group2[i], " condition ", tukeyData[tukeyData$`p adj` < 0.05,]$Comparison[i] , " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean2[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd2[i], 2), ")", ", ") } else if(nrow(tukeyData[tukeyData$`p adj` < 0.05,]) > 1 & i == nrow(tukeyData[tukeyData$`p adj` < 0.05,]) - 1){ text <- paste0(text," ", nameMeasure, " of the audios in the ", tukeyData[tukeyData$`p adj` < 0.05,]$group1[i], " condition", " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean1[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd1[i], 2), ")", " were significantly ", tukeyData[tukeyData$`p adj` < 0.05,]$comparison[i], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i], 2))))), ")", " than in the ", tukeyData$group2[i], " condition ", tukeyData[tukeyData$`p adj` < 0.05,]$Comparison[i] , " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean2[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd2[i], 2), ")", " and ") } else{ text <- paste0(text, " ", nameMeasure, " of the audios in the ", tukeyData[tukeyData$`p adj` < 0.05,]$group1[i], " condition", " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean1[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd1[i], 2), ")", " were significantly ", tukeyData[tukeyData$`p adj` < 0.05,]$comparison[i], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i], 2))))), ")", " than in the ", tukeyData$group2[i], " condition ", tukeyData[tukeyData$`p adj` < 0.05,]$Comparison[i] , " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean2[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd2[i], 2), ")", ".") } } } if(any(tukeyData$`p adj` > 0.05)){ text <- paste0(text, " However, no significant differences were found between ") for (i in 1:nrow(tukeyData[tukeyData$`p adj` > 0.05,])) { if(nrow(tukeyData[tukeyData$`p adj` > 0.05,]) > 1 & i < nrow(tukeyData[tukeyData$`p adj` > 0.05,]) - 1){ text <- paste0(text, rownames(tukeyData[tukeyData$`p adj` > 0.05,])[i], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i], 2))))) , ")" ,", ") } else if(nrow(tukeyData[tukeyData$`p adj` > 0.05,]) > 1 & i == nrow(tukeyData[tukeyData$`p adj` > 0.05,]) - 1){ text <- paste0(text, rownames(tukeyData[tukeyData$`p adj` > 0.05,])[i], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i], 2))))) , ") " , " and ") } else{ text <- paste0(text, rownames(tukeyData[tukeyData$`p adj` > 0.05,])[i], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[i], 2))))) , ")" , " conditions.") } } } } else{ text <- paste0("An analysis of variance (ANOVA) on ", nameMeasure, " did not yield significant variation among conditions, F(", AnovaTestData[[1]]["Condition",]$Df, ", ", AnovaTestData[[1]]["Residuals",]$Df, ") = ", round(AnovaTestData[[1]]["Condition",]$`F value`, 2), ", ", ifelse(AnovaTestData[[1]]["Condition",]$`Pr(>F)` < 0.001, "p < .001", ifelse(AnovaTestData[[1]]["Condition",]$`Pr(>F)` < 0.01, "p < .01", ifelse(AnovaTestData[[1]]["Condition",]$`Pr(>F)` < 0.05, "p < .05", paste("p = ", round(AnovaTestData[[1]]["Condition",]$`Pr(>F)`, 2))))), ".") if(any(tukeyData$`p adj` < 0.05)){ for (i in 1:nrow(tukeyData)) { tukeyData$mean1[i] <- mean(audioData[audioData$Condition == tukeyData$group1[i], measure]) tukeyData$mean2[i] <- mean(audioData[audioData$Condition == tukeyData$group2[i], measure]) tukeyData$comparison[i] <- ifelse(tukeyData$mean1[i] > tukeyData$mean2[i], "greater", ifelse(tukeyData$mean1[i] == tukeyData$mean2[i], "equal", "smaller")) tukeyData$sd1[i] <- sd(audioData[audioData$Condition == tukeyData$group1[i], measure]) tukeyData$sd2[i] <- sd(audioData[audioData$Condition == tukeyData$group2[i], measure]) } text <- paste0(text, " However, post hoc comparisons using the Tukey HSD Test indicated that ") for (i in 1:nrow(tukeyData[tukeyData$`p adj` < 0.05,])) { if(nrow(tukeyData[tukeyData$`p adj` < 0.05,]) > 1 & i < nrow(tukeyData[tukeyData$`p adj` < 0.05,]) - 1){ text <- paste0(text, " ", nameMeasure, " of the audios in the ", tukeyData[tukeyData$`p adj` < 0.05,]$group1[i], " condition", " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean1[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd1[i], 2), ")", " were significantly ", tukeyData[tukeyData$`p adj` < 0.05,]$comparison[i], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i], 2))))), ")", " than in the ", tukeyData$group2[i], " condition ", tukeyData[tukeyData$`p adj` < 0.05,]$Comparison[i] , " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean2[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd2[i], 2), ")", ", ") } else if(nrow(tukeyData[tukeyData$`p adj` < 0.05,]) > 1 & i == nrow(tukeyData[tukeyData$`p adj` < 0.05,]) - 1){ text <- paste0(text," ", nameMeasure, " of the audios in the ", tukeyData[tukeyData$`p adj` < 0.05,]$group1[i], " condition", " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean1[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd1[i], 2), ")", " were significantly ", tukeyData[tukeyData$`p adj` < 0.05,]$comparison[i], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i], 2))))), ")", " than in the ", tukeyData$group2[i], " condition ", tukeyData[tukeyData$`p adj` < 0.05,]$Comparison[i] , " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean2[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd2[i], 2), ")", " and ") } else{ text <- paste0(text, " ", nameMeasure, " of the audios in the ", tukeyData[tukeyData$`p adj` < 0.05,]$group1[i], " condition", " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean1[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd1[i], 2), ")", " were significantly ", tukeyData[tukeyData$`p adj` < 0.05,]$comparison[i], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[i], 2))))), ")", " than in the ", tukeyData$group2[i], " condition ", tukeyData[tukeyData$`p adj` < 0.05,]$Comparison[i] , " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean2[i], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd2[i], 2), ")", ".") } } } } } } else if(length(unique(audioData$Condition)) == 2){ if(min(normalityData$pValue)<0.05 & !avoidNormalCheck){ WilcoxonResults <- wilcox.test(as.formula(paste0(measure, "~", "Condition")), audioData) audioData$VarRank <- rank(audioData[,measure], ties.method = "average") SummaryData <- data.frame(condition1 = unique(audioData$Condition)[1], condition2 = unique(audioData$Condition)[2], meanRank1 = round(mean(audioData[audioData$Condition == unique(audioData$Condition)[1],"VarRank"]),2), meanRank2 = round(mean(audioData[audioData$Condition == unique(audioData$Condition)[2],"VarRank"]),2), comparison = NA) if(WilcoxonResults$p.value < 0.05){ SummaryData$comparison <- ifelse(SummaryData$meanRank1 > SummaryData$meanRank2, "higher", "lower") text <- paste0("A Wilcoxon Signed-Ranks Test indicated that ", nameMeasure, " mean rank was significantly ", SummaryData$comparison, " for ", SummaryData$condition1, " condition (Mean Rank = ", round(SummaryData$meanRank1, 2), ")" , " than ", SummaryData$condition2, " condition ", "(Mean Rank = ", round(SummaryData$meanRank2, 2), "), ", "Z = ", round(qnorm(WilcoxonResults$p.value/2), 2), ", ", ifelse(WilcoxonResults$p.value < 0.001, "p < .001", ifelse(WilcoxonResults$p.value < 0.01, "p < .01", ifelse(WilcoxonResults$p.value < 0.05, "p < .05", paste("p = ", round(WilcoxonResults$p.value, 2)))))) } else{ text <- paste0("A Wilcoxon Signed-Ranks Test did not show significant differences between ", SummaryData$condition1, " condition (Mean Rank = ", round(SummaryData$meanRank1, 2), ")" , " and ", SummaryData$condition2, " condition ", "(Mean Rank = ", round(SummaryData$meanRank2, 2), "), ", "Z = ", round(qnorm(WilcoxonResults$p.value/2), 2), ", ", ifelse(WilcoxonResults$p.value < 0.001, "p < .001", ifelse(WilcoxonResults$p.value < 0.01, "p < .01", ifelse(WilcoxonResults$p.value < 0.05, "p < .05", paste("p = ", round(WilcoxonResults$p.value, 2)))))) } } else{ ttestResults <- t.test(as.formula(paste0(measure, "~", "Condition")), audioData) SummaryData <- data.frame(condition1 = unique(audioData$Condition)[1], condition2 = unique(audioData$Condition)[2], mean1 = round(mean(audioData[audioData$Condition == unique(audioData$Condition)[1],measure]),2), mean2 = round(mean(audioData[audioData$Condition == unique(audioData$Condition)[2],measure]),2), sd1 = round(sd(audioData[audioData$Condition == unique(audioData$Condition)[1],measure]),2), sd2 = round(mean(audioData[audioData$Condition == unique(audioData$Condition)[2],measure]),2), comparison = NA) if(ttestResults$p.value < 0.05){ SummaryData$comparison <- ifelse(SummaryData$mean1 > SummaryData$mean2, "higher", "lower") text <- paste0("A T-Test indicated that ", nameMeasure," was significantly ", SummaryData$comparison, " for ", SummaryData$condition1, " condition (Mean = ", round(SummaryData$mean1, 2), ", SD = ", round(SummaryData$sd1, 2), ")" , " than ", SummaryData$condition2, " condition ", "(Mean = ", round(SummaryData$mean2, 2), ", SD = ", round(SummaryData$sd2, 2) ,"), ", "Z = ", round(qnorm(ttestResults$p.value/2), 2), ", ", ifelse(ttestResults$p.value < 0.001, "p < .001", ifelse(ttestResults$p.value < 0.01, "p < .01", ifelse(ttestResults$p.value < 0.05, "p < .05", paste("p = ", round(ttestResults$p.value, 2)))))) } else{ text <- paste0("A T-Test did not show significant differences in ", nameMeasure, " between ", SummaryData$condition1, " condition (Mean = ", round(SummaryData$mean1, 2), ", SD = ", round(SummaryData$sd1, 2), ")" , " and ", SummaryData$condition2, " condition ", "(Mean = ", round(SummaryData$mean2, 2), ", SD = ", round(SummaryData$sd2, 2) ,"), ", "Z = ", round(qnorm(ttestResults$p.value/2), 2), ", ", ifelse(ttestResults$p.value < 0.001, "p < .001", ifelse(ttestResults$p.value < 0.01, "p < .01", ifelse(ttestResults$p.value < 0.05, "p < .05", paste("p = ", round(ttestResults$p.value, 2)))))) } } } } if("Condition" %in% colnames(audioData) & "Dimension" %in% colnames(audioData) & includeDimensions){ if(min(normalityData$pValue)>=0.05){ res.aov1 <- aov(as.formula(paste(measure, "~", "Condition", "*", "Dimension")), data = audioData) res.aov2 <- summary(res.aov1) text <- paste0(toupper(substr(nameMeasure, 1, 1)), substr(nameMeasure, 2, nchar(nameMeasure)), " measure was subjected to a two-way analysis of variance having ", length(unique(audioData[,"Condition"])), " condition levels (", toString(unique(audioData[,"Condition"])), ") and ", length(unique(audioData[,"Dimension"])), " dimension levels (", toString(unique(audioData[,"Dimension"])),"). ") if(all(res.aov2[[1]]$`Pr(>F)`[-length(res.aov2[[1]]$`Pr(>F)`)] < 0.05)){ text <- paste0(text, " All effects were statistically significant at the 0.05 significance level.\n") } if(all(res.aov2[[1]]$`Pr(>F)`[-length(res.aov2[[1]]$`Pr(>F)`)] > 0.05)){ text <- paste0(text, " No significant statistically significant effects were found at the 0.05 significance level.\n") } if(any(res.aov2[[1]]$`Pr(>F)`[1:(length(res.aov2[[1]]$`Pr(>F)`)-2)] < 0.05, na.rm = TRUE)){ for (i in 1:(length(which(res.aov2[[1]]$`Pr(>F)`[1:(length(res.aov2[[1]]$`Pr(>F)`)-2)] < 0.05)))) { position <- which(res.aov2[[1]]$`Pr(>F)`[1:(length(res.aov2[[1]]$`Pr(>F)`)-2)] < 0.05)[i] text <- paste0(text, "There was a significant main effect for ", trimws(rownames(res.aov2[[1]])[position]), ", F(", res.aov2[[1]]$Df[position], ", ", res.aov2[[1]]["Residuals",]$Df, ") = ", round(res.aov2[[1]]$`F value`[position], 2), ", ", ifelse(res.aov2[[1]]$`Pr(>F)`[position] < 0.001, "p < .001", ifelse(res.aov2[[1]]$`Pr(>F)`[position] < 0.01, "p < .01", ifelse(res.aov2[[1]]$`Pr(>F)`[position] < 0.05, "p < .05", paste("p = ", round(res.aov2[[1]]$`Pr(>F)`[position], 2)))))) if(res.aov2[[1]]$`Pr(>F)`[length(res.aov2[[1]]$`Pr(>F)`)-1] > 0.05){ if(length(unique(audioData[,trimws(rownames(res.aov2[[1]])[i])])) > 2){ text <- paste0(text, ". ") tukeyData <- TukeyHSD(aov(as.formula(paste0(measure, "~", trimws(rownames(res.aov2[[1]])[position]))), data = audioData)) tukeyData <- as.data.frame(tukeyData[[trimws(rownames(res.aov2[[1]])[position])]]) tukeyData$group1 <- stringr::str_split(rownames(tukeyData), "-", simplify = T)[,1] tukeyData$group2 <- stringr::str_split(rownames(tukeyData), "-", simplify = T)[,2] rownames(tukeyData) <- stringr::str_replace(rownames(tukeyData), "-", " and ") if(any(tukeyData$`p adj` < 0.05)){ for (j in 1:nrow(tukeyData)) { tukeyData$mean1[j] <- mean(audioData[audioData[,trimws(rownames(res.aov2[[1]])[position])] == tukeyData$group1[j], measure], na.rm = TRUE) tukeyData$mean2[j] <- mean(audioData[audioData[,trimws(rownames(res.aov2[[1]])[position])] == tukeyData$group2[j], measure], na.rm = TRUE) tukeyData$comparison[j] <- ifelse(tukeyData$mean1[j] > tukeyData$mean2[j], "greater", ifelse(tukeyData$mean1[j] == tukeyData$mean2[j], "equal", "smaller")) tukeyData$sd1[j] <- sd(audioData[audioData[,trimws(rownames(res.aov2[[1]])[position])] == tukeyData$group1[j], measure], na.rm = TRUE) tukeyData$sd2[j] <- sd(audioData[audioData[,trimws(rownames(res.aov2[[1]])[position])] == tukeyData$group2[j], measure], na.rm = TRUE) } text <- paste0(text, " Post hoc comparisons using the Tukey HSD Test indicated that ") for (j in 1:nrow(tukeyData[tukeyData$`p adj` < 0.05,])) { if(nrow(tukeyData[tukeyData$`p adj` < 0.05,]) > 1 & j < nrow(tukeyData[tukeyData$`p adj` < 0.05,]) - 1){ text <- paste0(text, " ", nameMeasure, " of the audios in the ", tukeyData[tukeyData$`p adj` < 0.05,]$group1[j], " ", trimws(rownames(res.aov2[[1]])[position]), " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean1[j], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd1[j], 2), ")", " were significantly ", tukeyData[tukeyData$`p adj` < 0.05,]$comparison[j], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j], 2))))), ")", " than in the ", tukeyData$group2[j], " condition ", tukeyData[tukeyData$`p adj` < 0.05,]$Comparison[j] , " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean2[j], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd2[j], 2), ")", ", ") } else if(nrow(tukeyData[tukeyData$`p adj` < 0.05,]) > 1 & j == nrow(tukeyData[tukeyData$`p adj` < 0.05,]) - 1){ text <- paste0(text," ", nameMeasure, " of the audios in the ", tukeyData[tukeyData$`p adj` < 0.05,]$group1[j], " ", trimws(rownames(res.aov2[[1]])[position]), " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean1[j], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd1[j], 2), ")", " were significantly ", tukeyData[tukeyData$`p adj` < 0.05,]$comparison[j], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j], 2))))), ")", " than in the ", tukeyData$group2[j], " condition ", tukeyData[tukeyData$`p adj` < 0.05,]$Comparison[j] , " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean2[j], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd2[j], 2), ")", " and ") } else{ text <- paste0(text, " ", nameMeasure, " of the audios in the ", tukeyData[tukeyData$`p adj` < 0.05,]$group1[j], " ", trimws(rownames(res.aov2[[1]])[position]), " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean1[j], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd1[j], 2), ")", " were significantly ", tukeyData[tukeyData$`p adj` < 0.05,]$comparison[j], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$`p adj`[j], 2))))), ")", " than in the ", tukeyData$group2[j], " condition ", tukeyData[tukeyData$`p adj` < 0.05,]$Comparison[j] , " (M = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$mean2[j], 2), ", SD = ", round(tukeyData[tukeyData$`p adj` < 0.05,]$sd2[j], 2), ")", ".") } } } if(any(tukeyData$`p adj` > 0.05)){ text <- paste0(text, " However, no significant differences were found between ") for (j in 1:nrow(tukeyData[tukeyData$`p adj` > 0.05,])) { if(nrow(tukeyData[tukeyData$`p adj` > 0.05,]) > 1 & j < nrow(tukeyData[tukeyData$`p adj` > 0.05,]) - 1){ text <- paste0(text, rownames(tukeyData[tukeyData$`p adj` > 0.05,])[j], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j], 2))))), ")" ,", ") } else if(nrow(tukeyData[tukeyData$`p adj` > 0.05,]) > 1 & j == nrow(tukeyData[tukeyData$`p adj` > 0.05,]) - 1){ text <- paste0(text, rownames(tukeyData[tukeyData$`p adj` > 0.05,])[j], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j], 2))))), ") " , " and ") } else{ text <- paste0(text, rownames(tukeyData[tukeyData$`p adj` > 0.05,])[j], " (Holm-Bonferroni adjusted ", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j] < 0.001, "p < .001", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j] < 0.01, "p < .01", ifelse(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j] < 0.05, "p < .05", paste("p = ", round(tukeyData[tukeyData$`p adj` > 0.05,]$`p adj`[j], 2))))), ")" , " conditions.") } } } } else if(length(unique(audioData[,trimws(rownames(res.aov2[[1]])[i])])) == 2){ comparisonTable <- data.frame(Name1 = unique(audioData[,trimws(rownames(res.aov2[[1]])[i])])[1], Mean1 = round(mean(audioData[audioData[,trimws(rownames(res.aov2[[1]])[i])] == unique(audioData[,trimws(rownames(res.aov2[[1]])[i])])[1], measure], na.rm = TRUE), 2), SD1 = round(sd(audioData[audioData[,trimws(rownames(res.aov2[[1]])[i])] == unique(audioData[,trimws(rownames(res.aov2[[1]])[i])])[1], measure], na.rm = TRUE), 2), Name2 = unique(audioData[,trimws(rownames(res.aov2[[1]])[i])])[2], Mean2 = round(mean(audioData[audioData[,trimws(rownames(res.aov2[[1]])[i])] == unique(audioData[,trimws(rownames(res.aov2[[1]])[i])])[2], measure], na.rm = TRUE), 2), SD2 = round(sd(audioData[audioData[,trimws(rownames(res.aov2[[1]])[i])] == unique(audioData[,trimws(rownames(res.aov2[[1]])[i])])[2], measure], na.rm = TRUE), 2)) comparisonTable$relationship <- ifelse(comparisonTable$Mean1 > comparisonTable$Mean2, "greater", "smaller") text <- paste0(text, ", such that the average ", nameMeasure, " was significantly ", comparisonTable$relationship, " for ", comparisonTable$Name1, " (M = ", comparisonTable$Mean1, ", SD = ", comparisonTable$SD1, ") than for ", comparisonTable$Name2, " (M = ", comparisonTable$Mean2, ", SD = ", comparisonTable$SD2, ").") } } else{ text <- paste0(text, ". ") } } } if(any(res.aov2[[1]]$`Pr(>F)`[1:(length(res.aov2[[1]]$`Pr(>F)`)-1)] > 0.05, na.rm = TRUE)) { for (i in 1:(length(which(res.aov2[[1]]$`Pr(>F)`[1:(length(res.aov2[[1]]$`Pr(>F)`)-1)] > 0.05)))) { position <- which(res.aov2[[1]]$`Pr(>F)`[1:(length(res.aov2[[1]]$`Pr(>F)`)-1)] > 0.05)[i] if(any(res.aov2[[1]]$`Pr(>F)`[1:(length(res.aov2[[1]]$`Pr(>F)`)-1)] < 0.05, na.rm = TRUE) & i == 1){ text <- paste0(text, " However,") if(position == (length(res.aov2[[1]]$`Pr(>F)`)-1)){ text <- paste0(text, " the interaction effect") } else{ text <- paste0(text, " the main effect of ", trimws(rownames(res.aov2[[1]])[i])) } } else{ if(position == (length(res.aov2[[1]]$`Pr(>F)`)-1)){ text <- paste0(text, " The interaction effect") } else{ text <- paste0(text, " The main effect of ", trimws(rownames(res.aov2[[1]])[i])) } } text <- paste0(text, " was non-significant, F(", res.aov2[[1]]$Df[i], ", ", res.aov2[[1]]["Residuals",]$Df, ") = ", round(res.aov2[[1]]$`F value`[i], 2), ", ", ifelse(res.aov2[[1]]$`Pr(>F)`[i] < 0.001, "p < .001", ifelse(res.aov2[[1]]$`Pr(>F)`[i] < 0.01, "p < .01", ifelse(res.aov2[[1]]$`Pr(>F)`[i] < 0.05, "p < .05", paste("p = ", round(res.aov2[[1]]$`Pr(>F)`[i], 2))))), ". ") } } if(res.aov2[[1]]$`Pr(>F)`[(length(res.aov2[[1]]$`Pr(>F)`)-1)] < 0.05){ position <- length(res.aov2[[1]]$`Pr(>F)`)-1 text <- paste0(text, " The interaction effect was significant", ", F(", res.aov2[[1]]$Df[position], ", ", res.aov2[[1]]["Residuals",]$Df, ") = ", round(res.aov2[[1]]$`F value`[position], 2), ", ", ifelse(res.aov2[[1]]$`Pr(>F)`[position] < 0.001, "p < .001", ifelse(res.aov2[[1]]$`Pr(>F)`[position] < 0.01, "p < .01", ifelse(res.aov2[[1]]$`Pr(>F)`[position] < 0.05, "p < .05", paste("p = ", round(res.aov2[[1]]$`Pr(>F)`[position], 2))))), ".") MeanData <- do.call(data.frame,aggregate(as.formula(paste(measure, "~", "Condition", "*", "Dimension")), data = audioData, FUN = function(x) c(mean = mean(x, na.rm = TRUE), n = round(length(x),0), sd = sd(x, na.rm = TRUE)))) colnames(MeanData) <- c("Condition", "Dimension", "Mean", "N", "SD") SimpleMainEffectsTable <- phia::testInteractions(res.aov2, fixed = "Condition", across = "Dimension") if(any(SimpleMainEffectsTable$`Pr(>F)`[1:(length(SimpleMainEffectsTable$`Pr(>F)`)-1)] < 0.05, na.rm = TRUE)){ text <- paste0(text, " Simple main effects analysis showed that ", measure, " was ") for(i in 1:(length(which(SimpleMainEffectsTable$`Pr(>F)`[1:(length(SimpleMainEffectsTable$`Pr(>F)`)-1)] < 0.05)))){ position <- which(SimpleMainEffectsTable$`Pr(>F)`[1:(length(SimpleMainEffectsTable$`Pr(>F)`)-1)] < 0.05)[i] for(j in 1:(length(unique(audioData$Dimension))-1)){ text <- paste0(text, "significantly ", ifelse(sign(SimpleMainEffectsTable[position, j]) == "-", "smaller", "greater"), " for the ", unique(audioData$Dimension)[1], " dimension than for the ", unique(audioData$Dimension)[j+1], " dimension in the ", trimws(rownames(SimpleMainEffectsTable)[position]), " condition (p = ", round(SimpleMainEffectsTable$`Pr(>F)`[position], 2), ")") if((length(unique(audioData$Dimension))-1) > 1 & j != (length(unique(audioData$Dimension))-1)){ text <- paste0(text, "; ") } } if(i == (length(which(SimpleMainEffectsTable$`Pr(>F)`[1:(length(SimpleMainEffectsTable$`Pr(>F)`)-1)] < 0.05)))){ text <- paste0(text, ". ") } else{ text <- paste0(text, "; ") } } } if(any(SimpleMainEffectsTable$`Pr(>F)`[1:(length(SimpleMainEffectsTable$`Pr(>F)`)-1)] > 0.05, na.rm = TRUE)){ if(any(SimpleMainEffectsTable$`Pr(>F)`[1:(length(SimpleMainEffectsTable$`Pr(>F)`)-1)] < 0.05, na.rm = TRUE)){ text <- paste0(text, " However, there were no significant differences") } else{ text <- paste0(text, " Simple main effects analysis showed that there were no significant differences for ", measure) } for(i in 1:(length(which(SimpleMainEffectsTable$`Pr(>F)`[1:(length(SimpleMainEffectsTable$`Pr(>F)`)-1)] > 0.05)))){ position <- which(SimpleMainEffectsTable$`Pr(>F)`[1:(length(SimpleMainEffectsTable$`Pr(>F)`)-1)] > 0.05)[i] for(j in 1:(length(unique(audioData$Dimension))-1)){ text <- paste0(text, " between ", unique(audioData$Dimension)[1], " dimension and ", unique(audioData$Dimension)[j+1], " dimension in the ", trimws(rownames(SimpleMainEffectsTable)[position]), " condition (p = ", round(SimpleMainEffectsTable$`Pr(>F)`[position], 2), ")") if((length(unique(audioData$Dimension))-1) > 1 & j != (length(unique(audioData$Dimension))-1)){ text <- paste0(text, "; ") } } if(i == (length(which(SimpleMainEffectsTable$`Pr(>F)`[1:(length(SimpleMainEffectsTable$`Pr(>F)`)-1)] > 0.05)))){ text <- paste0(text, ". ") } else{ text <- paste0(text, "; ") } } } } } else{ res.schreirer <- rcompanion::scheirerRayHare(as.formula(paste(measure, "~", "Condition", "*", "Dimension")), audioData, verbose = FALSE) text <- paste0(toupper(substr(nameMeasure, 1, 1)), substr(nameMeasure, 2, nchar(nameMeasure)), " measure was subjected to a Scheirer-Ray-Hare test having ", length(unique(audioData[,"Condition"])), " condition levels (", toString(unique(audioData[,"Condition"])), ") and ", length(unique(audioData[,"Dimension"])), " dimension levels (", toString(unique(audioData[,"Dimension"])),"). ") if(all(res.schreirer$p.value[-length(res.schreirer$p.value)] < 0.05)){ text <- paste0(text, " All effects were statistically significant at the 0.05 significance level.\n") } if(all(res.schreirer$p.value[-length(res.schreirer$p.value)] > 0.05)){ text <- paste0(text, " No statistically significant effects were found at the 0.05 significance level.\n") } if(any(res.schreirer$p.value[1:(length(res.schreirer$p.value)-2)] < 0.05, na.rm = TRUE)){ for (i in 1:(length(which(res.schreirer$p.value[1:(length(res.schreirer$p.value)-2)] < 0.05)))) { position <- which(res.schreirer$p.value[1:(length(res.schreirer$p.value)-2)] < 0.05)[i] text <- paste0(text, "There was a significant main effect for ", trimws(rownames(res.schreirer)[position]), ", H(", res.schreirer$Df[position], ") = ", round(res.schreirer$H[position], 2), ", ", ifelse(res.schreirer$p.value[position] < 0.001, "p < .001", ifelse(res.schreirer$p.value[position] < 0.01, "p < .01", ifelse(res.schreirer$p.value[position] < 0.05, "p < .05", paste("p = ", round(res.schreirer$p.value[position], 2)))))) if(res.schreirer$p.value[length(res.schreirer$p.value)-1] > 0.05 & length(unique(audioData[,trimws(rownames(res.schreirer)[position])])) > 2){ text <- paste0(text, ". ") audioData$VarRank <- rank(audioData[,measure], ties.method = "average") dunnData <- FSA::dunnTest(as.formula(paste0(measure, "~", trimws(rownames(res.schreirer)[position]))), data = audioData) dunnData$res$Comparison <- stringr::str_replace(dunnData$res$Comparison, "-", "and") if(any(dunnData$res$P.adj < 0.05)){ text <- paste0(text, " Post hoc comparisons using the Dunn's Test showed significant differences in ", nameMeasure, "'s mean rank between ") for (j in 1:nrow(dunnData$res[dunnData$res$P.adj < 0.05,])) { if(nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) > 1 & j < nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) - 1){ text <- paste0(text, dunnData$res[dunnData$res$P.adj < 0.05,]$Comparison[j], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j], 2))))), ")" ,", ") } else if(nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) > 1 & j == nrow(dunnData$res[dunnData$res$P.adj < 0.05,]) - 1){ text <- paste0(text, dunnData$res[dunnData$res$P.adj < 0.05,]$Comparison[j], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j], 2))))), ") " , " and ") } else{ text <- paste0(text, dunnData$res[dunnData$res$P.adj < 0.05,]$Comparison[j], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj < 0.05,]$P.adj[j], 2))))), ")" , ".") } } if(any(dunnData$res$P.adj > 0.05)){ text <- paste0(text, " However, no significant differences were found between ") for (j in 1:nrow(dunnData$res[dunnData$res$P.adj > 0.05,])) { if(nrow(dunnData$res[dunnData$res$P.adj > 0.05,]) > 1 & j < nrow(dunnData$res[dunnData$res$P.adj > 0.05,]) - 1){ text <- paste0(text, dunnData$res[dunnData$res$P.adj > 0.05,]$Comparison[j], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj > 0.05,]$P.adj[j] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj > 0.05,]$P.adj[j] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj > 0.05,]$P.adj[j] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj > 0.05,]$P.adj[j], 2))))), ")" ,", ") } else if(nrow(dunnData$res[dunnData$res$P.adj > 0.05,]) > 1 & j == nrow(dunnData$res[dunnData$res$P.adj > 0.05,]) - 1){ text <- paste0(text, dunnData$res[dunnData$res$P.adj > 0.05,]$Comparison[j], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[j] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[j] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[j] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[j], 2))))), ") " , "and ") } else{ text <- paste0(text, dunnData$res[dunnData$res$P.adj > 0.05,]$Comparison[j], " (Holm-Bonferroni adjusted ", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[j] < 0.001, "p < .001", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[j] < 0.01, "p < .01", ifelse(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[j] < 0.05, "p < .05", paste("p = ", round(dunnData$res[dunnData$res$P.adj > 0.05,]$P.adj[j], 2))))), ")" , trimws(rownames(res.schreirer)[position]), ". ") } } } } if(all(dunnData$res$P.adj > 0.05)){ text <- paste0(text, " Although, post hoc comparisons using the Dunn's Test did not show any significant differences in ", nameMeasure, "'s mean rank. ") } } } } } } return(text) } ``` This is an automatically generated report by VoiceR. # Statistics Table ```{r Statistics Table, echo=FALSE, message=FALSE, warning=FALSE} DT::datatable(params$audioData, options = list(pageLength = 10, scrollX = TRUE)) ``` # Normality Plots ```{r include=FALSE} audioData <- params$audioData text <- createNormalityText(audioData, "duration", "duration", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[1], BoxCoxConstant = params$avoidNormalCheck[9]) ``` **Duration** `r text` ```{r include=FALSE} text <- createNormalityText(audioData, "voice_breaks_percent", "voice breaks percentage", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[2], BoxCoxConstant = params$avoidNormalCheck[10]) ``` **Voice Breaks Percentage** `r text` ```{r include=FALSE} normalPlots <- params$normalPlots for (j in 1:length(params$normalPlots)) { normalPlots[[j]]$layers[[2]] <- NULL normalPlots[[j]]$layer[[2]] <- NULL } ``` ```{r Normal Plot 1 and 2, echo=FALSE, message=FALSE, warning=FALSE, out.width="50%"} if(!is.null(normalPlots[[1]])) normalPlots[[1]] + ggplot2::labs(title="Density Plot of Audio Duration \n by Condition") + ggthemes::theme_fivethirtyeight() if(!is.null(normalPlots[[2]])) normalPlots[[2]] + ggplot2::labs(title="Density Plot of Voice Breaks Percentage \n by Condition") + ggthemes::theme_fivethirtyeight() ``` ```{r include=FALSE} text <- createNormalityText(audioData, "RMS_env", "RMS of Amplitude envelope", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[3], BoxCoxConstant = params$avoidNormalCheck[11]) ``` **Root Mean Square (RMS) of Amplitude envelope** `r text` ```{r include=FALSE} text <- createNormalityText(audioData, "mean_loudness", "loudness", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[4], BoxCoxConstant = params$avoidNormalCheck[12]) ``` **Loudness** `r text` ```{r Normal Plot 3 and 4, echo=FALSE, message=FALSE, warning=FALSE, out.width="50%"} if(!is.null(normalPlots[[3]])) normalPlots[[3]] + ggplot2::labs(title="Density Plot of RMS of the amplitude envelope \n by Condition") + ggthemes::theme_fivethirtyeight() if(!is.null(normalPlots[[4]])) normalPlots[[4]] + ggplot2::labs(title="Density Plot of Loudness \n by Condition") + ggthemes::theme_fivethirtyeight() ``` ```{r include=FALSE} text <- createNormalityText(audioData, "mean_F0", "average pitch", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[5], BoxCoxConstant = params$avoidNormalCheck[13]) ``` **Mean Fundamental Frequency (F0)** `r text` ```{r include=FALSE} text <- createNormalityText(audioData, "sd_F0", "pitch's standard deviation", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[6], BoxCoxConstant = params$avoidNormalCheck[14]) ``` **Standard Deviation (sd) of F0** `r text` ```{r Normal Plot 5 and 6, echo=FALSE, message=FALSE, warning=FALSE, out.width="50%"} if(!is.null(normalPlots[[5]])) normalPlots[[5]] + ggplot2::labs(title="Density Plot of Average Pitch \n by Condition") + ggthemes::theme_fivethirtyeight() if(!is.null(normalPlots[[6]])) normalPlots[[6]] + ggplot2::labs(title="Density Plot of Pitch's Standard Deviation \n by Condition") + ggthemes::theme_fivethirtyeight() ``` ```{r include=FALSE} text <- createNormalityText(audioData, "mean_entropy", "average Wiener entropy", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[7], BoxCoxConstant = params$avoidNormalCheck[15]) ``` **Average Wiener Entropy** `r text` ```{r include=FALSE} text <- createNormalityText(audioData, "mean_HNR", "average Harmonics-to-Noise Ratio", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[8], BoxCoxConstant = params$avoidNormalCheck[16]) ``` **Average Harmonics-to-Noise Ratio** `r text` ```{r Normal Plot 7 and 8, echo=FALSE, message=FALSE, warning=FALSE, out.width="50%"} normalPlots[[7]] + ggplot2::labs(title="Density Plot of Average Entropy \n by Condition") + ggthemes::theme_fivethirtyeight() normalPlots[[8]] + ggplot2::labs(title="Density Plot of Average Harmonics-to-Noise Ratio \n by Condition") + ggthemes::theme_fivethirtyeight() ``` # Comparison Plots ```{r include=FALSE} text <- createComparisonText(audioData, "duration", "duration", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[1]) ``` **Duration** `r text` ```{r include=FALSE} text <- createComparisonText(audioData, "voice_breaks_percent", "voice breaks percentage", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[2]) ``` **Voice Breaks Percentage** `r text` ```{r Plot 1 and 2, echo=FALSE, message=FALSE, warning=FALSE, out.width="50%"} comparisons <- params$comparisons if(params$includeDimensions){ if(!is.null(comparisons[[1]])) comparisons[[1]]$layers[[2]] <- NULL if(!is.null(comparisons[[2]])) comparisons[[2]]$layers[[2]] <- NULL if(!is.null(comparisons[[3]])) comparisons[[3]]$layers[[2]] <- NULL if(!is.null(comparisons[[4]])) comparisons[[4]]$layers[[2]] <- NULL if(!is.null(comparisons[[5]])) comparisons[[5]]$layers[[2]] <- NULL if(!is.null(comparisons[[6]])) comparisons[[6]]$layers[[2]] <- NULL if(!is.null(comparisons[[7]])) comparisons[[7]]$layers[[2]] <- NULL if(!is.null(comparisons[[8]])) comparisons[[8]]$layers[[2]] <- NULL } if(!is.null(comparisons[[1]])) comparisons[[1]] + ggplot2::labs(title="Plot of Audio Duration \n by Condition") + ggthemes::theme_fivethirtyeight() + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), axis.line.x = ggplot2::element_line(), axis.line.y = ggplot2::element_line()) if(!is.null(comparisons[[2]])) comparisons[[2]] + ggplot2::labs(title="Plot of Voice Breaks Percentage \n by Condition") + ggthemes::theme_fivethirtyeight() + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), axis.line.x = ggplot2::element_line(), axis.line.y = ggplot2::element_line()) ``` ```{r include=FALSE} text <- createComparisonText(audioData, "RMS_env", "RMS of the amplitude envelope", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[3]) ``` **RMS of the amplitude envelope** `r text` ```{r include=FALSE} text <- createComparisonText(audioData, "mean_loudness", "loudness", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[4]) ``` **Loudness** `r text` ```{r Plot 3 and 4, echo=FALSE, message=FALSE, warning=FALSE, out.width="50%"} if(!is.null(comparisons[[3]])) comparisons[[3]] + ggplot2::labs(title="Plot of RMS of the amplitude envelope \n by Condition") + ggthemes::theme_fivethirtyeight() + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), axis.line.x = ggplot2::element_line(), axis.line.y = ggplot2::element_line()) if(!is.null(comparisons[[4]])) comparisons[[4]] + ggplot2::labs(title="Plot of Loudness \n by Condition") + ggthemes::theme_fivethirtyeight() + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), axis.line.x = ggplot2::element_line(), axis.line.y = ggplot2::element_line()) ``` ```{r include=FALSE} text <- createComparisonText(audioData, "mean_F0", "average Pitch", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[5]) ``` **Average Pitch** `r text` ```{r include=FALSE} text <- createComparisonText(audioData, "sd_F0", "pitch's Standard Deviation", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[6]) ``` **SD Pitch** `r text` ```{r Plot 5 and 6, echo=FALSE, message=FALSE, warning=FALSE, out.width="50%"} if(!is.null(comparisons[[5]])) comparisons[[5]] + ggplot2::labs(title="Plot of Average F0 \n by Condition") + ggthemes::theme_fivethirtyeight() + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), axis.line.x = ggplot2::element_line(), axis.line.y = ggplot2::element_line()) if(!is.null(comparisons[[6]])) comparisons[[6]] + ggplot2::labs(title="Plot of F0 Standard Deviation \n by Condition") + ggthemes::theme_fivethirtyeight() + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), axis.line.x = ggplot2::element_line(), axis.line.y = ggplot2::element_line()) ``` ```{r include=FALSE} text <- createComparisonText(audioData, "mean_entropy", "average Entropy", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[7]) ``` **Average Entropy** `r text` ```{r include=FALSE} text <- createComparisonText(audioData, "mean_HNR", "average Harmonics-to-Noise Ratio", includeDimensions = params$includeDimensions, avoidNormalCheck = params$avoidNormalCheck[8]) ``` **Average Harmonics-to-Noise Ratio** `r text` ```{r Plot 7 and 8, echo=FALSE, message=FALSE, warning=FALSE, out.width="50%"} if(!is.null(comparisons[[7]])) comparisons[[7]] + ggplot2::labs(title="Plot of Average Entropy \n by Condition") + ggthemes::theme_fivethirtyeight() + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), axis.line.x = ggplot2::element_line(), axis.line.y = ggplot2::element_line()) if(!is.null(comparisons[[8]])) comparisons[[8]] + ggplot2::labs(title="Plot of Average Harmonics-To-Noise Ratio \n by Condition") + ggthemes::theme_fivethirtyeight() + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), axis.line.x = ggplot2::element_line(), axis.line.y = ggplot2::element_line()) ``` # Appendices {.tabset} ## Appendix A: General Data Information ```{r echo=FALSE, warning=FALSE} nameMeasures = c("Duration", "Voice Breaks Percentage", "RMS of the amplitude envelope", "Loudness", "Avg. Pitch", "Pitch SD", "Avg Entropy", "Avg HNR") figureNumber = 1 tableSummary(audioData, by = c(), figureNumber = paste0("A", figureNumber), nameMeasures = nameMeasures) ``` ```{r echo=FALSE, warning=FALSE} if("Condition" %in% colnames(audioData)){ figureNumber <- figureNumber + 1 tableSummary(audioData, by = c("Condition"), figureNumber = paste0("A", figureNumber), nameMeasures = nameMeasures) } ``` ```{r echo=FALSE, warning=FALSE} if("Dimension" %in% colnames(audioData) & params$includeDimensions){ figureNumber <- figureNumber + 1 tableSummary(audioData, by = c("Dimension"), figureNumber = paste0("A", figureNumber), nameMeasures = nameMeasures) } ``` ```{r echo=FALSE, warning=FALSE} if("Dimension" %in% colnames(audioData) & params$includeDimensions){ figureNumber <- figureNumber + 1 tableSummary(audioData, by = c("Condition", "Dimension"), figureNumber = paste0("A", figureNumber), nameMeasures = nameMeasures) } ``` ## Appendix B: Normality Tables {.tabset .tabset-pills} ### Duration ```{r echo=FALSE, message=FALSE, warning=FALSE} #Duration Normality durationNormalityTable <- tableNormality(audioData, "duration", includeDimensions = params$includeDimensions) figureNumber <- 1 tableNormality(audioData, "duration", nameMeasure = "Duration", includeDimensions = params$includeDimensions, HTMLTable = TRUE, figureNumber = paste0("B", figureNumber)) ``` ### Voice Breaks Percentage ```{r echo=FALSE, message=FALSE, warning=FALSE} #voice_breaks_percent Normality voicedPercentNormalityTable <- tableNormality(audioData, "voice_breaks_percent", includeDimensions = params$includeDimensions) figureNumber <- figureNumber + 1 tableNormality(audioData, "voice_breaks_percent", nameMeasure = "Voice Breaks Percentage",includeDimensions = params$includeDimensions, HTMLTable = TRUE, figureNumber = paste0("B", figureNumber)) ``` ### RMS of the amplitude envelope ```{r echo=FALSE, message=FALSE, warning=FALSE} #RMS amplitude Normality RMSamplitudeNormalityTable <- tableNormality(audioData, "RMS_env", includeDimensions = params$includeDimensions) figureNumber <- figureNumber + 1 tableNormality(audioData, "RMS_env", nameMeasure = "RMS of the amplitude envelope",includeDimensions = params$includeDimensions, HTMLTable = TRUE, figureNumber = paste0("B", figureNumber)) ``` ### Loudness ```{r echo=FALSE, message=FALSE, warning=FALSE} #Loudness amplitude Normality loudnessNormalityTable <- tableNormality(audioData, "mean_loudness", includeDimensions = params$includeDimensions) figureNumber <- figureNumber + 1 tableNormality(audioData, "mean_loudness", nameMeasure = "Loudness",includeDimensions = params$includeDimensions, HTMLTable = TRUE, figureNumber = paste0("B", figureNumber)) ``` ### Mean Pitch ```{r echo=FALSE, message=FALSE, warning=FALSE} #Pitch pitchNormalityTable <- tableNormality(audioData, "mean_F0", includeDimensions = params$includeDimensions) figureNumber <- figureNumber + 1 tableNormality(audioData, "mean_F0", nameMeasure = "Average F0",includeDimensions = params$includeDimensions, HTMLTable = TRUE, figureNumber = paste0("B", figureNumber)) ``` ### SD Pitch ```{r echo=FALSE, message=FALSE, warning=FALSE} #SD Pitch sdPitchNormalityTable <- tableNormality(audioData, "sd_F0", includeDimensions = params$includeDimensions) figureNumber <- figureNumber + 1 tableNormality(audioData, "sd_F0", nameMeasure = "F0 Standard Deviation",includeDimensions = params$includeDimensions, HTMLTable = TRUE, figureNumber = paste0("B", figureNumber)) ``` ### Entropy ```{r echo=FALSE, message=FALSE, warning=FALSE} #Entropy entropyNormalityTable <- tableNormality(audioData, "mean_entropy", includeDimensions = params$includeDimensions) figureNumber <- figureNumber + 1 tableNormality(audioData, "mean_entropy", nameMeasure = "Average Entropy",includeDimensions = params$includeDimensions, HTMLTable = TRUE, figureNumber = paste0("B", figureNumber)) ``` ### HNR ```{r echo=FALSE, message=FALSE, warning=FALSE} #HNR hnrNormalityTable <- tableNormality(audioData, "mean_HNR", includeDimensions = params$includeDimensions) figureNumber <- figureNumber + 1 tableNormality(audioData, "mean_HNR", nameMeasure = "Average Harmonics-to-Noise Ratio",includeDimensions = params$includeDimensions, HTMLTable = TRUE, figureNumber = paste0("B", figureNumber)) ``` ## Appendix C: Comparison Tests {.tabset .tabset-pills} ```{r include=FALSE} TablesToGenerate <- function(audioData, measure, nameMeasure, includeDimensions, isNormal){ TablesToReport <- vector(mode = "numeric", length = 13) figureNumber <- 0 if(as.logical(includeDimensions)){ if(isNormal){ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 1 formula = as.formula(paste(measure, "~ Condition * Dimension")) AnovaTestData <- summary(aov(formula, audioData))[[1]] if(AnovaTestData$`Pr(>F)`[3] < 0.05){ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 2 } else{ if(AnovaTestData$`Pr(>F)`[1] < 0.05){ if(length(unique(audioData$Condition)) > 2){ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 3 } } if(AnovaTestData$`Pr(>F)`[2] < 0.05){ if(length(unique(audioData$Dimension)) > 2){ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 4 } } } } else{ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 5 formula = as.formula(paste(measure, "~ Condition * Dimension")) res.schreirer <- rcompanion::scheirerRayHare(as.formula(paste(measure, "~ Condition * Dimension")), audioData, verbose = FALSE) if(res.schreirer$p.value[3] < 0.05){ } else{ if(res.schreirer$p.value[1] < 0.05){ if(length(unique(audioData$Condition)) > 2){ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 6 } } if(res.schreirer$p.value[2] < 0.05){ if(length(unique(audioData$Dimension)) > 2){ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 7 } } } } }else{ if(isNormal){ if(length(unique(audioData$Condition)) > 2){ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 8 formula = as.formula(paste(measure, "~ Condition")) AnovaTestData <- summary(aov(formula, audioData))[[1]] if(AnovaTestData$`Pr(>F)`[1] < 0.05){ if(length(unique(audioData$Condition)) > 2){ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 9 } } } else{ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 13 } } else{ if(length(unique(audioData$Condition)) > 2){ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 10 figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 11 formula = as.formula(paste(measure, "~ Condition")) kruskalTestData <- kruskal.test(formula, audioData) if(kruskalTestData$p.value < 0.05){ if(length(unique(audioData$Condition)) > 2){ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 12 } } } else{ figureNumber <- figureNumber + 1 TablesToReport[figureNumber] <- 13 } } } return(TablesToReport) } ``` ### Duration ```{r echo=FALSE, warning=FALSE} measure <- "duration" nameMeasure <- "Duration" if(sum(!is.na(audioData[,measure])) >= 3){ isNormal <- (min(durationNormalityTable$pValue) >= 0.05 | as.logical(params$avoidNormalCheck[1])) TablesToReport <- TablesToGenerate(audioData, measure, nameMeasure, params$includeDimensions, isNormal) }else{ TablesToReport <- c() } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(1 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 1) tableANOVA(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(2 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 2) tableSimpleMainEffects(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(3 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 3) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(4 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 4) tableTukey(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(5 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 5) tableSchreirer(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(6 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 6) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(7 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 7) tableDunn(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(8 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 8) tableANOVA(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(9 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 9) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(10 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 10) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = TRUE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(11 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 11) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = FALSE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(12 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 12) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(13 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ cat("No tables generated for t-test") } ``` ### Voice Breaks Percentage ```{r echo=FALSE, warning=FALSE} measure <- "voice_breaks_percent" nameMeasure <- "Voice Breaks Percentage" if(sum(!is.na(audioData[,measure])) >= 3){ isNormal <- (min(voicedPercentNormalityTable$pValue) >= 0.05 | params$avoidNormalCheck[2]) TablesToReport <- TablesToGenerate(audioData, measure, nameMeasure, params$includeDimensions, isNormal) }else{ TablesToReport <- c() } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(1 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 1) tableANOVA(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(2 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 2) tableSimpleMainEffects(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(3 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 3) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(4 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 4) tableTukey(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(5 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 5) tableSchreirer(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(6 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 6) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(7 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 7) tableDunn(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(8 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 8) tableANOVA(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(9 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 9) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(10 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 10) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = TRUE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(11 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 11) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = FALSE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(12 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 12) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(13 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ print("No tables generated for t-test") } ``` ### RMS of the amplitude envelope ```{r echo=FALSE, warning=FALSE} measure <- "RMS_env" nameMeasure <- "RMS of the amplitude envelope" if(sum(!is.na(audioData[,measure])) >= 3){ isNormal <- (min(RMSamplitudeNormalityTable$pValue) >= 0.05 | params$avoidNormalCheck[3]) TablesToReport <- TablesToGenerate(audioData, measure, nameMeasure, params$includeDimensions, isNormal) }else{ TablesToReport <- c() } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(1 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 1) tableANOVA(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(2 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 2) tableSimpleMainEffects(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(3 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 3) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(4 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 4) tableTukey(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(5 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 5) tableSchreirer(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(6 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 6) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(7 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 7) tableDunn(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(8 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 8) tableANOVA(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(9 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 9) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(10 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 10) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = TRUE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(11 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 11) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = FALSE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(12 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 12) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(13 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ print("No tables generated for t-test") } ``` ### Loudness ```{r echo=FALSE, warning=FALSE} measure <- "mean_loudness" nameMeasure <- "Loudness" if(sum(!is.na(audioData[,measure])) >= 3){ isNormal <- (min(loudnessNormalityTable$pValue) >= 0.05 | params$avoidNormalCheck[4]) TablesToReport <- TablesToGenerate(audioData, measure, nameMeasure, params$includeDimensions, isNormal) }else{ TablesToReport <- c() } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(1 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 1) tableANOVA(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(2 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 2) tableSimpleMainEffects(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(3 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 3) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(4 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 4) tableTukey(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(5 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 5) tableSchreirer(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(6 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 6) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(7 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 7) tableDunn(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(8 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 8) tableANOVA(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(9 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 9) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(10 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 10) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = TRUE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(11 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 11) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = FALSE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(12 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 12) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(13 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ print("No tables generated for t-test") } ``` ### Mean F0 ```{r echo=FALSE, warning=FALSE} measure <- "mean_F0" nameMeasure <- "Avg. Fundamental Frequency" if(sum(!is.na(audioData[,measure])) >= 3){ isNormal <- (min(pitchNormalityTable$pValue) >= 0.05 | params$avoidNormalCheck[5]) TablesToReport <- TablesToGenerate(audioData, measure, nameMeasure, params$includeDimensions, isNormal) }else{ TablesToReport <- c() } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(1 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 1) tableANOVA(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(2 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 2) tableSimpleMainEffects(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(3 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 3) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(4 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 4) tableTukey(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(5 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 5) tableSchreirer(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(6 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 6) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(7 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 7) tableDunn(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(8 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 8) tableANOVA(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(9 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 9) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(10 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 10) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = TRUE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(11 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 11) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = FALSE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(12 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 12) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(13 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ print("No tables generated for t-test") } ``` ### SD F0 ```{r echo=FALSE, warning=FALSE} measure <- "sd_F0" nameMeasure <- "F0 Standard Deviation" if(sum(!is.na(audioData[,measure])) >= 3){ isNormal <- (min(sdPitchNormalityTable$pValue) >= 0.05 | params$avoidNormalCheck[6]) TablesToReport <- TablesToGenerate(audioData, measure, nameMeasure, params$includeDimensions, isNormal) }else{ TablesToReport <- c() } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(1 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 1) tableANOVA(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(2 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 2) tableSimpleMainEffects(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(3 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 3) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(4 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 4) tableTukey(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(5 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 5) tableSchreirer(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(6 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 6) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(7 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 7) tableDunn(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(8 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 8) tableANOVA(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(9 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 9) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(10 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 10) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = TRUE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(11 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 11) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = FALSE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(12 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 12) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(13 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ print("No tables generated for t-test") } ``` ### Mean Entropy ```{r echo=FALSE, warning=FALSE} measure <- "mean_entropy" nameMeasure <- "Average Entropy" if(sum(!is.na(audioData[,measure])) >= 3){ isNormal <- (min(entropyNormalityTable$pValue) >= 0.05 | params$avoidNormalCheck[7]) TablesToReport <- TablesToGenerate(audioData, measure, nameMeasure, params$includeDimensions, isNormal) }else{ TablesToReport <- c() } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(1 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 1) tableANOVA(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(2 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 2) tableSimpleMainEffects(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(3 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 3) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(4 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 4) tableTukey(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(5 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 5) tableSchreirer(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(6 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 6) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(7 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 7) tableDunn(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(8 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 8) tableANOVA(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(9 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 9) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(10 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 10) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = TRUE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(11 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 11) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = FALSE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(12 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 12) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(13 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ print("No tables generated for t-test") } ``` ### Mean HNR ```{r echo=FALSE, warning=FALSE} measure <- "mean_HNR" nameMeasure <- "Average Harmonics-to-Noise Ratio" if(sum(!is.na(audioData[,measure])) >= 3){ isNormal <- (min(hnrNormalityTable$pValue) >= 0.05 | params$avoidNormalCheck[8]) TablesToReport <- TablesToGenerate(audioData, measure, nameMeasure, params$includeDimensions, isNormal) }else{ TablesToReport <- c() } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(1 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 1) tableANOVA(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(2 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 2) tableSimpleMainEffects(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(3 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 3) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(4 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 4) tableTukey(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(5 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 5) tableSchreirer(audioData, by = c("Condition", "Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(6 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 6) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(7 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 7) tableDunn(audioData, by = c("Dimension"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(8 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 8) tableANOVA(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(9 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 9) tableTukey(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(10 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 10) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = TRUE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(11 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 11) tableKruskal(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber), InfoTable = FALSE) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(12 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ figureNumber <- which(TablesToReport == 12) tableDunn(audioData, by = c("Condition"), measure = measure, nameMeasure = nameMeasure, figureNumber = paste0("C", figureNumber)) } ``` ```{r echo=FALSE, message=FALSE, warning=FALSE} if(13 %in% TablesToReport && sum(!is.na(audioData[,measure])) >= 3){ print("No tables generated for t-test") } ```
/scratch/gouwar.j/cran-all/cranData/voiceR/inst/AppShiny/report.Rmd
server <- function(input, output) { volumes <- shinyFiles::getVolumes()() shinyFiles::shinyDirChoose( input, 'dir', roots = c(Home = volumes), filetypes = c('', 'wav', 'mp3') ) shinyjs::hide("AnalysisData") shinyjs::hide("downloadReport") shinyjs::hide("ResultTable") shinyjs::hide("splitN1") shinyjs::hide("splitN2") shinyjs::hide("splitN3") shinyjs::hide("splitN4") shinyjs::hide("split1") shinyjs::hide("split2") shinyjs::hide("split3") shinyjs::hide("split4") global <- shiny::reactiveValues(datapath = getwd()) updatedText <- "" dir <- shiny::reactive(input$dir) output$dir <- shiny::renderText({ global$datapath }) shiny::observeEvent(ignoreNULL = TRUE, eventExpr = { input$dir }, handlerExpr = { if (!"path" %in% names(dir())) return() home <- normalizePath(volumes, winslash = "/") home <- stringr::str_replace(home, "/", "\\") paths <- file.path(home, paste(unlist(dir()$path[-1]), collapse = "/")) paths <- paths[sapply(paths, dir.exists)] global$datapath <- paths }) patternShiny <- shiny::reactive(input$patternRaw) files <- 0 shiny::observeEvent(input$doAnalysis, { shinyjs::html(id = "titleMain", html = "", add = FALSE) shinyjs::html(id = "MainList", html = "", add = FALSE) shinyjs::hide("downloadReport") shinyjs::hide("AnalysisData") shinyjs::hide("ErrorTable") shinyjs::hide("ResultTable") shinyjs::hide("splitN1") shinyjs::hide("splitN2") shinyjs::hide("splitN3") shinyjs::hide("splitN4") shinyjs::hide("split1") shinyjs::hide("split2") shinyjs::hide("split3") shinyjs::hide("split4") pattern <- trimws(strsplit(patternShiny(), ",")[[1]]) if(length(pattern) == 0){ pattern <- c() } else { pattern = paste(pattern,collapse="|") } files <- list.files(path = global$datapath, pattern = pattern, recursive = input$recursive) fileType <- tolower(input$fileType) files <- files[grep(paste0("\\.", fileType), files)] if(length(files) > 0){ print(files) processedNames <- basename(stringr::str_remove_all(files, pattern = paste0("\\.", fileType))) } checkPattern <- stringr::str_split(input$fileNamePattern, input$sep, simplify = TRUE) checkPattern <- tolower(checkPattern) patternCorrectness <- checkPattern %in% c("id", "condition", "dimension", "null") if(length(checkPattern[!patternCorrectness]) >= 1){ output$NumberFiles <- renderText(paste("Incorrect Components:", checkPattern[!patternCorrectness])) } else if(length(files) == 0){ output$NumberFiles <- renderText(paste("No Audio Files Found in", global$datapath)) } else if(!"dimension" %in% checkPattern && input$includeDimensions){ output$NumberFiles <- renderText(paste("Attention: Include Dimensions defined but no Dimension in the pattern")) } else if(input$normalizeData && length(processedNames)){ output$NumberFiles <- renderText(paste("Attention: Not enough data to use the normalization feature.")) } else{ componentsAndPositions <- getComponents(processedNames, input$fileNamePattern, input$sep) ids <- unique(componentsAndPositions[["Components"]][,componentsAndPositions[["Positions"]][["ID"]]]) if(componentsAndPositions[["Positions"]][["Condition"]] == 99){ conditions <- "" conditionPresence <- FALSE }else{ conditions <- unique(componentsAndPositions[["Components"]][,"Condition"]) conditionPresence <- TRUE } if(componentsAndPositions[["Positions"]][["Dimension"]] == 99){ dimensions <- "" dimensionPresence <- FALSE }else{ dimensions <- unique(componentsAndPositions[["Components"]][,"Dimension"]) dimensionPresence <- TRUE } Description <- paste0(as.character(length(files)), " audio files have been analyzed\n", length(ids), " unique IDs, ", ifelse(length(conditions) == 1, ifelse(conditions == "", 0, length(conditions)), length(conditions)), " unique conditions and ", ifelse(length(dimensions) == 1, ifelse(dimensions == "", 0, length(dimensions)), length(dimensions)), " unique dimensions.") output$NumberFiles <- renderText(Description) shinyjs::html(id = "titleMain", html = "<h1> 1 - Reading Audio Files </h1>", add = FALSE) audioList <- vector("list",length(files)) shiny::withProgress(message = 'Step 1: Reading Files', value = 0, { i <- 1 for (file in files) { if(input$fileType == "WAV"){ audioList[[i]] <- tuneR::readWave(paste(global$datapath, "/", file, sep = "")) } else{ audioList[[i]] <- tuneR::readMP3(paste(global$datapath, "/", file, sep = "")) } names(audioList)[i] <- basename(stringr::str_remove_all(file, pattern = paste0("\\.", fileType))) i <- i + 1 textToShow <- paste0("<div class = 'soundFile'> <span class= 'audioIcon'><img src='https://img.icons8.com/cute-clipart/64/000000/audio-file.png'/></span><span class= 'audioName'>", basename(stringr::str_remove_all(file, pattern = paste0("\\.", fileType))), "</span> </div>" ) shinyjs::html(id = "MainList", html = textToShow, add = TRUE) shiny::incProgress(1/length(files), detail = paste(i, "files read")) } }) Sys.sleep(2.5) shinyjs::html(id = "titleMain", html = "", add = FALSE) shinyjs::html(id = "MainList", html = "", add = FALSE) if(input$preprocess){ shinyjs::html(id = "titleMain", html = "<h1> Preprocessing Audio Files </h1>", add = TRUE) shiny::withProgress(message = 'Preprocessing Files', value = 0, { preprocess(audioList, verbose = FALSE, progress=TRUE) }) } shinyjs::html(id = "titleMain", html = "", add = FALSE) shinyjs::html(id = "MainList", html = "", add = FALSE) Sys.sleep(2.5) measures <- c("duration", "voice_breaks_percent", "RMS_env", "mean_loudness", "mean_F0", "sd_F0", "mean_entropy", "mean_HNR") audioData <- as.data.frame(matrix(nrow = length(files), ncol = length(measures))) errors <- vector(length = length(files)) errorNumber <- 0 row.names(audioData) <- basename(stringr::str_remove_all(files, pattern = paste0("\\.", fileType))) colnames(audioData) <- measures components <- getComponents(rownames(audioData), input$fileNamePattern, input$sep) if(dimensionPresence){ audioData <- cbind("Dimension" = components[["Components"]][,"Dimension"], audioData) } if(conditionPresence){ audioData <- cbind("Condition" = components[["Components"]][,"Condition"], audioData) } audioData <- cbind("ID" = components[["Components"]][,"ID"], audioData) shinyjs::html(id = "titleMain", html = "<h1> 2 - Analyzing Audio Files </h1>", add = TRUE) shiny::withProgress(message = 'Step 2: Analyzing Files', value = 0, { cl <- parallel::makeCluster(parallel::detectCores() - 2) doParallel::registerDoParallel(cl) for(i in 1:length(audioList)) { tryCatch({ errorTest <- NULL audioName <- names(audioList)[i] componentsAndPositions <- getComponents(audioName, input$fileNamePattern, input$sep) id <- componentsAndPositions[["Components"]][,componentsAndPositions[["Positions"]][["ID"]]] sound_orig = as.numeric(scale(audioList[[audioName]]@left)) samplingRate = audioList[[audioName]]@samp.rate if(conditionPresence & dimensionPresence & input$includeDimensions){ dimension <- componentsAndPositions[["Components"]][,"Dimension"] Condition <- componentsAndPositions[["Components"]][,"Condition"] } else if(conditionPresence){ Condition <- componentsAndPositions[["Components"]][,"Condition"] } else if(dimensionPresence){ dimension <- componentsAndPositions[["Components"]][,"Dimension"] } rowsFilter <- which(rownames(audioData) %in% names(audioList)[i]) if(input$preprocess){ analyzeData <- soundgen::analyze(audioList[[audioName]]@left, samplingRate = audioList[[audioName]]@samp.rate, plot = FALSE, osc = FALSE, summaryFun = c("mean", "sd")) analyzeData <- analyzeData$summary } else{ analyzeData <- soundgen::analyze(audioList[[audioName]]@left, samplingRate = audioList[[audioName]]@samp.rate, plot = FALSE, osc = FALSE, summaryFun = c("mean", "sd")) analyzeData <- analyzeData$summary } audioData[rowsFilter, measures[1]] <- seewave::duration(audioList[[audioName]]) audioData[rowsFilter, measures[2]] <- 1 - analyzeData$voiced audioData[rowsFilter, measures[3]] <- seewave::rms(seewave::env(seewave::zapsilw(audioList[[audioName]], plot = FALSE),f=audioList[[audioName]]@samp.rate, plot = FALSE)) audioData[rowsFilter, measures[4]] <- analyzeData$loudness_mean audioData[rowsFilter, measures[5]] <- analyzeData$pitch_mean audioData[rowsFilter, measures[6]] <- analyzeData$pitch_sd audioData[rowsFilter, measures[7]] <- analyzeData$entropy_mean audioData[rowsFilter, measures[8]] <- analyzeData$HNR_mean errorTest <- audioData[rowsFilter, measures[1]] textToShow <- paste0("<div class = 'soundFile'> <span class= 'audioIcon'><img src='https://img.icons8.com/cute-clipart/64/000000/audio-file.png'/></span><span class= 'audioName'>", audioName, "</span> <span style='margin-right: 30px; float: right;'><img src='https://img.icons8.com/fluent/48/000000/checked.png'/></div>" ) shinyjs::html(id = "MainList", html = textToShow, add = TRUE) shiny::incProgress(1/length(files), detail = paste(i, "files analyzed")) }, error = function(e) { print(e) textToShow <- paste0("<div class = 'soundFile'> <span class= 'audioIcon'><img src='https://img.icons8.com/cute-clipart/64/000000/audio-file.png'/></span><span class= 'audioName'>", audioName, "</span> <span style='margin-right: 30px; float: right;'><img src='https://img.icons8.com/emoji/48/000000/cross-mark-emoji.png'/></div>" ) shinyjs::html(id = "MainList", html = textToShow, add = TRUE) }, finally ={if(is.null(errorTest)){ errorNumber <- errorNumber + 1 errors[errorNumber] <- audioName }}) } parallel::stopCluster(cl) if(input$normalizeData){ audioData <- normalizeData(audioData = audioData, includeDimensions = input$includeDimensions, includeConditions = conditionPresence) avoidNormalCheck <- audioData$avoidNormalCheck audioData <- audioData$audioData } else{ avoidNormalCheck <- rep(FALSE, length(measures)) } comparisons <- tryCatch({ if((conditionPresence & !dimensionPresence) | (conditionPresence & !input$includeDimensions)){ print("Doing Comparisons - Condition") comparisons <- comparisonPlots(audioData, "Condition", avoidNormalCheck = input$normalizeData) } else if(conditionPresence & dimensionPresence & input$includeDimensions){ print("Doing Comparisons - Condition + Dimension") comparisons <- comparisonPlots(audioData, c("Condition", "Dimension"), avoidNormalCheck = input$normalizeData) } else if(!conditionPresence & dimensionPresence){ print("Doing Comparisons - Dimension") comparisons <- comparisonPlots(audioData, c("Dimension"), avoidNormalCheck = input$normalizeData) } else{ print("No comparisons") comparisons <- comparisonPlots(audioData, avoidNormalCheck = input$normalizeData) } }, error=function(e) { comparisons <- NULL }) if(is.null(comparisons)){ output$NumberFiles <- renderText("Not enough data for comparisons") } else{ if(nrow(audioData) > 3){ normalPlots <- normalityPlots(audioData) } else{ normalPlots <- NULL } rownames(audioData) <- c() Sys.sleep(2.5) shinyjs::html(id = "titleMain", html = "", add = FALSE) shinyjs::html(id = "MainList", html = "", add = FALSE) shinyjs::show("AnalysisData", anim = TRUE, time = 1) shinyjs::show("ResultTable", anim = TRUE, time = 1) shinyjs::show("ErrorTable", anim = TRUE, time = 1) output$ResultTable = DT::renderDataTable({ audioData }, server = FALSE, extensions = 'Buttons', options = list( scrollX = TRUE, dom = 'Bfrtip', buttons = list('copy', 'print', list( extend = 'collection', buttons = list( list(extend = 'csv', filename = "AudioData"), list(extend = 'excel', filename = "AudioData"), list(extend = 'pdf', filename = "AudioData")), text = 'Download') ) )) errors <- data.frame(File = errors[errors != "FALSE"], Status = rep("Error", length(errors[errors != "FALSE"]))) output$ErrorTable = DT::renderDataTable({ errors }, server = FALSE, extensions = 'Buttons', options = list( scrollX = TRUE, dom = 'Bfrtip', buttons = list('copy', 'print', list( extend = 'collection', buttons = list( list(extend = 'csv', filename = "AudioData"), list(extend = 'excel', filename = "AudioData"), list(extend = 'pdf', filename = "AudioData")), text = 'Download') ) )) shinyjs::show("splitN1", anim = TRUE, time = 1) shinyjs::show("splitN2", anim = TRUE, time = 1) shinyjs::show("splitN3", anim = TRUE, time = 1) shinyjs::show("splitN4", anim = TRUE, time = 1) shinyjs::show("split1", anim = TRUE, time = 1) shinyjs::show("split2", anim = TRUE, time = 1) shinyjs::show("split3", anim = TRUE, time = 1) shinyjs::show("split4", anim = TRUE, time = 1) if(!is.null(normalPlots$duration)) output$normalPlot1 <- plotly::renderPlotly(plotly::ggplotly(normalPlots$duration + ggplot2::labs(title="Density Plot of Audio Duration \n by Condition")+ ggthemes::theme_fivethirtyeight())) if(!is.null(normalPlots$voice_breaks_percent)) output$normalPlot2 <- plotly::renderPlotly(plotly::ggplotly(normalPlots$voice_breaks_percent + ggplot2::labs(title="Density Plot of Voice Breaks Percentage \n by Condition") + ggthemes::theme_fivethirtyeight())) if(!is.null(normalPlots$RMS_env)) output$normalPlot3 <- plotly::renderPlotly(plotly::ggplotly(normalPlots$RMS_env + ggplot2::labs(title="Density Plot of RMS of the amplitude envelope \n by Condition") + ggthemes::theme_fivethirtyeight())) if(!is.null(normalPlots$mean_loudness)) output$normalPlot4 <- plotly::renderPlotly(plotly::ggplotly(normalPlots$mean_loudness + ggplot2::labs(title="Density Plot of Loudness \n by Condition") + ggthemes::theme_fivethirtyeight())) if(!is.null(normalPlots$mean_F0)) output$normalPlot5 <- plotly::renderPlotly(plotly::ggplotly(normalPlots$mean_F0 + ggplot2::labs(title="Density Plot of Average F0 \n by Condition") + ggthemes::theme_fivethirtyeight())) if(!is.null(normalPlots$sd_F0)) output$normalPlot6 <- plotly::renderPlotly(plotly::ggplotly(normalPlots$sd_F0 + ggplot2::labs(title="Density Plot of F0 Standard Deviation \n by Condition") + ggthemes::theme_fivethirtyeight())) if(!is.null(normalPlots$mean_entropy)) output$normalPlot7 <- plotly::renderPlotly(plotly::ggplotly(normalPlots$mean_entropy + ggplot2::labs(title="Density Plot of Average Entropy \n by Condition") + ggthemes::theme_fivethirtyeight())) if(!is.null(normalPlots$mean_HNR)) output$normalPlot8 <- plotly::renderPlotly(plotly::ggplotly(normalPlots$mean_HNR + ggplot2::labs(title="Density Plot of Average Harmonics-To-Noise Ratio \n by Condition") + ggthemes::theme_fivethirtyeight())) if(!input$includeDimensions){ output$plot1 <- plotly::renderPlotly(plotly::ggplotly(comparisons$duration + ggplot2::ylim(min( audioData[, measures[1]]), max(audioData[, measures[1]])*1.1) + ggplot2::labs(title="Plot of Audio Duration \n by Condition") + ggthemes::theme_fivethirtyeight())) output$plot2 <- plotly::renderPlotly(plotly::ggplotly(comparisons$voice_breaks_percent + ggplot2::ylim(min( audioData[, measures[2]]), max(audioData[, measures[2]])*1.1) + ggplot2::labs(title="Plot of Voice Breaks Percentage \n by Condition") + ggthemes::theme_fivethirtyeight())) output$plot3 <- plotly::renderPlotly(plotly::ggplotly(comparisons$RMS_env + ggplot2::ylim(min( audioData[, measures[3]]), max(audioData[, measures[3]])*1.1) + ggplot2::labs(title="Plot of RMS of the amplitude envelope \n by Condition") + ggthemes::theme_fivethirtyeight())) output$plot4 <- plotly::renderPlotly(plotly::ggplotly(comparisons$mean_loudness + ggplot2::ylim(min( audioData[, measures[4]]), max(audioData[, measures[4]])*1.1) + ggplot2::labs(title="Plot of Loudness \n by Condition") + ggthemes::theme_fivethirtyeight())) output$plot5 <- plotly::renderPlotly(plotly::ggplotly(comparisons$mean_F0 + ggplot2::ylim(min( audioData[, measures[5]]), max(audioData[, measures[5]])*1.1) + ggplot2::labs(title="Plot of Average F0 \n by Condition") + ggthemes::theme_fivethirtyeight())) output$plot6 <- plotly::renderPlotly(plotly::ggplotly(comparisons$sd_F0 + ggplot2::ylim(min( audioData[, measures[6]]), max(audioData[, measures[6]])*1.1) + ggplot2::labs(title="Plot of F0 Standard Deviation \n by Condition") + ggthemes::theme_fivethirtyeight())) output$plot7 <- plotly::renderPlotly(plotly::ggplotly(comparisons$mean_entropy + ggplot2::ylim(min( audioData[, measures[7]]), max(audioData[, measures[7]])*1.1) + ggplot2::labs(title="Plot of Average Entropy \n by Condition") + ggthemes::theme_fivethirtyeight())) output$plot8 <- plotly::renderPlotly(plotly::ggplotly(comparisons$mean_HNR + ggplot2::ylim(min( audioData[, measures[8]]), max(audioData[, measures[8]])*1.1) + ggplot2::labs(title="Plot of Average Harmonics-To-Noise Ratio \n by Condition") + ggthemes::theme_fivethirtyeight())) } else{ convertDimensionsAndConditionsPlot <- function(plot, measure, nameMeasure){ ggplotData <- ggplot2::ggplot_build(plot) grobData <- capture.output(ggplotData$plot$layers[[2]]) grobData <- paste0(grobData, collapse = " ") grobData <- stringr::str_split(grobData, ",") grobData <- grobData[[1]] grobData <- grobData[stringr::str_detect(grobData, "label = .*")] grobData <- stringr::str_extract(grobData, '\".*\"') grobData <- stringr::str_remove_all(grobData, '\"') grobDataFrame <- data.frame(C1 = grobData[3:5] ,C2 = grobData[6:8]) colnames(grobDataFrame) <- grobData[1:2] fig <- plotly::plot_ly( type = 'table', domain = list(x=c(0.3,0.7)), header = list( values = c( names(grobDataFrame)), align = c("center", "center"), line = list(width = 1, color = 'black'), font = list(family = "Arial", size = 14, color = "black") ), cells = list( values = rbind( t(as.matrix(unname(grobDataFrame))) ), align = c("center", "center"), font = list(family = "Arial", size = 12, color = c("black")) )) fig2 <- plotly::layout(plotly::ggplotly(plot + ggplot2::ylim(min( audioData[, measure]), max(audioData[, measure])*1.1) + ggplot2::labs(title=paste0("Plot of Audio ", paste(toupper(substr(nameMeasure, 1, 1)), substr(nameMeasure, 2, nchar(measure)), sep=""), "\n by Condition")) + ggthemes::theme_fivethirtyeight()), boxmode = "group") final <- plotly::subplot(fig, fig2, nrows = 2, which_layout = 2) return(plotly::layout(final, yaxis = list(domain = c(0.8, 1)), yaxis2 = list(domain = c(0, 0.8)), legend = list(x = 1.01, y = 0.41))) } if(!is.null(comparisons$duration)) output$plot1 <- plotly::renderPlotly(convertDimensionsAndConditionsPlot(comparisons$duration, measures[[1]], "duration")) if(!is.null(comparisons$voice_breaks_percent)) output$plot2 <- plotly::renderPlotly(convertDimensionsAndConditionsPlot(comparisons$voice_breaks_percent, measures[[2]], "Voice Breaks Percentage")) if(!is.null(comparisons$RMS_env)) output$plot3 <- plotly::renderPlotly(convertDimensionsAndConditionsPlot(comparisons$RMS_env, measures[[3]], "RMS of the amplitude envelope")) if(!is.null(comparisons$mean_loudness)) output$plot4 <- plotly::renderPlotly(convertDimensionsAndConditionsPlot(comparisons$mean_loudness, measures[[4]], "Loudness")) if(!is.null(comparisons$mean_F0)) output$plot5 <- plotly::renderPlotly(convertDimensionsAndConditionsPlot(comparisons$mean_F0, measures[[5]], "Average F0")) if(!is.null(comparisons$sd_F0)) output$plot6 <- plotly::renderPlotly(convertDimensionsAndConditionsPlot(comparisons$sd_F0, measures[[6]], "F0 standard Deviation")) if(!is.null(comparisons$mean_entropy)) output$plot7 <- plotly::renderPlotly(convertDimensionsAndConditionsPlot(comparisons$mean_entropy, measures[[7]], "Average entropy")) if(!is.null(comparisons$mean_HNR)) output$plot8 <- plotly::renderPlotly(convertDimensionsAndConditionsPlot(comparisons$mean_HNR, measures[[8]], "Average Harmonics-To-Noise Ratio")) } comparisons2 <- list() normalPlots2 <- list() for (i in 1:length(measures)) { measure <- measures[i] comparisons2[[i]] <- comparisons[[measure]] normalPlots2[[i]] <- normalPlots[[measure]] } shinyjs::show("downloadReport") params <<- list(audioData = audioData, comparisons = comparisons2, normalPlots = normalPlots2, avoidNormalCheck = avoidNormalCheck, includeDimensions = input$includeDimensions) } }) } }) output$downloadReport <- shiny::downloadHandler( filename = "report.html", content = function(file) { src <- normalizePath('report.Rmd') # temporarily switch to the temp dir, in case you do not have write # permission to the current working directory owd <- setwd(tempdir()) on.exit(setwd(owd)) file.copy(src, 'report.Rmd', overwrite = TRUE) out <- rmarkdown::render('report.Rmd', rmarkdown::html_document(), params = params) file.rename(out, file) } ) }
/scratch/gouwar.j/cran-all/cranData/voiceR/inst/AppShiny/server.R
ui <- fluidPage( # Application title shinyjs::useShinyjs(), tags$head( shiny::tags$style(shiny::HTML(" @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap'); .soundFile { background-color: #1B1B1B; background-position: center; max-width: 900px; margin: 30px auto 0 auto; text-align: left; color: white; font-style: italic; font-size: 16px; border: 2px solid #222; border-width: 2px; box-shadow: 0 0 5px black; padding: 7px 0; transition: all 200ms; background: #444; } .shinyDirectories.btn{ margin-bottom: 5px; box-shadow: inset 0px 0px 15px 3px #2e495e; background: linear-gradient(to bottom, #4F6276 5%, #607184 100%); background-color: #394e66; border-radius: 8px; border: 1px solid #1f2f47; display: inline-block; cursor: pointer; color: #ffffff; font-family: Arial; font-size: 15px; padding: 6px 13px; text-decoration: none; text-shadow: 0px 1px 0px #273a75; } #downloadReport{ margin-bottom: 15px; } .audioIcon{ display: inline-block; margin-left: 30px; margin-right: 25%; } .shiny-split-layout img{ width: 97%; height: 97%; } .shiny-split-layout{ text-align: center; margin-top: 30px; margin-bottom: 30px; box-shadow: 0 0 5px #d3d3d3; border: 2px solid #d3d3d3; border-width: 2px; padding: 7px 0; transition: all 200ms; background: #ededed; } #NumberFiles{ margin-top: 15px; } #ResultTable{ margin-top: 30px; margin-bottom: 30px; } .hero{ height: 30vh; display: flex; justify-content: center; text-align: center; color: white; align-items: center; background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url(https://images.unsplash.com/photo-1589903308904-1010c2294adc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80); background-size: cover; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; } .hero-text { /* Text styles */ font-size: 5em; margin-top: 0; margin-bottom: 0.5em; } #doAnalysis{ font-size: 1.4rem; font-weight: 500; fill: #fff; color: #fff; background-color: #00a6e7; border-style: solid; border-width: 2px; border-color: #00a6e7; border-radius: 2px; padding: 16px 30px; } .well{ background: linear-gradient(to right, #243B55, #141E30); opacity: .98; transition: background .3s,border-radius .3s,opacity .3s; box-shadow: 0 0 5px black; border: 2px solid #222; margin-top: 2vh; color: white; margin-left: 15px; } .container-fluid{ background: #ECE9E6; /* fallback for old browsers */ background: -webkit-linear-gradient(to right, #FFFFFF, #ECE9E6); /* Chrome 10-25, Safari 5.1-6 */ background: linear-gradient(to right, #FFFFFF, #ECE9E6); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */ padding-right: 0px; padding-left: 0px; margin-right: 0px; margin-left: 0px; } .row{ display: flex; flex-wrap: wrap; margin-right: 0px; margin-left: 0px; word-break: normal; } .span5{ margin-right: 20px; } html{ background: #ECE9E6; /* fallback for old browsers */ background: -webkit-linear-gradient(to right, #FFFFFF, #ECE9E6); /* Chrome 10-25, Safari 5.1-6 */ background: linear-gradient(to right, #FFFFFF, #ECE9E6); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */ font-family: 'Roboto', sans-serif; } ")) ), shiny::div(class = "hero", shiny::div(class = "hero-text", shiny::h1("VoiceR: voice Analytics for R"), shiny::HTML('<img src="https://www.ibt.unisg.ch/wp-content/uploads/2021/08/IBTLogoSquares_NZ.png" width = "90", height = "90"/>'))), shiny::sidebarPanel( shinyFiles::shinyDirButton("dir", "Input directory", "Upload"), shiny::verbatimTextOutput("dir", placeholder = TRUE), withTags(div(class='row', div(class='span5', shiny::checkboxInput("recursive", "Recursive", value = FALSE, width = NULL)), div(class='span5', shiny::checkboxInput("preprocess", "Preprocess", value = FALSE, width = NULL)), div(class='span5', shiny::checkboxInput("includeDimensions", "Include Dimensions", value = FALSE, width = NULL)), div(class='span5', shiny::checkboxInput("normalizeData", "Transform data to normal", value = FALSE, width = NULL)) )), shiny::textInput("sep", "File Name Separator", value = "_"), shiny::textInput("fileNamePattern", "File Name Pattern", value = "ID_Condition"), shiny::textInput("patternRaw", 'Data Selection Filter (comma separated)', placeholder = "345abd, 456hf, Inside"), shiny::selectInput("fileType", "File Type:", choices=c("WAV", "MP3")), shiny::actionButton("doAnalysis", "Analyze") ), shiny::mainPanel( shiny::div(id = "titleMain", shiny::h1("Instructions")), shiny::verbatimTextOutput("NumberFiles", placeholder = FALSE), shiny::div(id = "MainList", p("The voiceR shiny app simplifies the process of analyzing and comparing multiple audio files, removing any need to code. "), shiny::p("It requires the file names to follow a specific pattern, in which the different components (IDs, and in case of different conditions and/or dimensions, conditions and dimensions) are separated by a non alphanumeric character, regardless of their order. Examples of valid patterns would be 876h_Exterior (ID_Condition), Exterior-876h (Condition_ID), 876h_Exterior_q1 (ID_Condition_Dimension)."), shiny::strong("All file names to be analysed in a run should follow the same file name pattern."), shiny::p("To use it, you must first click the 'Input Directory' button and select the directory where the audio files to be analyzed are located. In addition, if you also want to analyze audio files that are in folders within the selected directory, the recursive checkbox should be checked. Likewise, to automatically pre-process the audio files before analyzing them, the 'pre-process' checkbox should be checked. Also, in case that your data included a Dimensions component and you wanted to include it in the comparison graphs, check the 'Include Dimensions?' box"), shiny::p("In addition, the separator between the different components must be specified in the field 'Field Name Separator' and the pattern that follows the name of the files must be specified in 'File Name Pattern'. In case the pattern includes more components than you want to analyze, they can be ignored (as long as they are in the last positions) and will not be taken into account in the analyses. For example, if the pattern is ID_Condition_Dimension but only the ID is to be taken into account, then it should be defined as the ID pattern, and if the Dimension is also to be taken into account, then it should be defined as the ID_Condition pattern."), shiny::p("The 'Data Selection Filter (comma separated)' field allows you to select the different audio files that should be read by defining comma separated patterns. For example if you want to select audio files containing ID 08788 and 065678, plus the interior condition you should define in this field: 08788, 065678, interior."), shiny::p("Finally, the correct File Type should be selected. And the analyze button should be clicked in order to start the analysis."), shiny::p("In case you want to try the app with some test data, you can download it ", shiny::a("here.", href = "https://osf.io/zt5h2/?view_only=348d1d172435449391e8d64547716477"))), tabsetPanel( id = "AnalysisData", tabPanel("Analysis Data", DT::dataTableOutput("ResultTable")), tabPanel("Errors", DT::dataTableOutput("ErrorTable")) ), shiny::splitLayout(id = "splitN1", cellWidths = c("49%", "49%"), plotly::plotlyOutput("normalPlot1"), plotly::plotlyOutput("normalPlot2")), shiny::splitLayout(id = "splitN2", cellWidths = c("49%", "49%"), plotly::plotlyOutput("normalPlot3"), plotly::plotlyOutput("normalPlot4")), shiny::splitLayout(id = "splitN3", cellWidths = c("49%", "49%"), plotly::plotlyOutput("normalPlot5"), plotly::plotlyOutput("normalPlot6")), shiny::splitLayout(id = "splitN4", cellWidths = c("49%", "49%"), plotly::plotlyOutput("normalPlot7"), plotly::plotlyOutput("normalPlot8")), shiny::splitLayout(id = "split1", cellWidths = c("49%", "49%"), plotly::plotlyOutput("plot1"), plotly::plotlyOutput("plot2")), shiny::splitLayout(id = "split2", cellWidths = c("49%", "49%"), plotly::plotlyOutput("plot3"), plotly::plotlyOutput("plot4")), shiny::splitLayout(id = "split3", cellWidths = c("49%", "49%"), plotly::plotlyOutput("plot5"), plotly::plotlyOutput("plot6")), shiny::splitLayout(id = "split4", cellWidths = c("49%", "49%"), plotly::plotlyOutput("plot7"), plotly::plotlyOutput("plot8")), shiny::downloadButton('downloadReport') ))
/scratch/gouwar.j/cran-all/cranData/voiceR/inst/AppShiny/ui.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' @name PolarVolume-class #' @title PolarVolume #' @description The polar volume object as defined by RAVE. #' @keywords internal NULL #' @name RaveIO-class #' @title RaveIO routines #' @description Provides I/O routines using the rave framework #' @keywords internal NULL #' @name Vol2BirdConfig-class #' @title Vol2Bird configuration #' @description The vol2bird configuration used during processing #' @keywords internal #' @seealso [vol2bird_config()] NULL #' @name Vol2Bird-class #' @title Vol2Bird processor class #' @description The vol2bird processing class. #' Provides methods for processing polar volumes/scans. #' @keywords internal #' @seealso [vol2bird()] NULL #' @rdname PolarVolume-class #' @name Rcpp_PolarVolume-class #' @title Rcpp_PolarVolume-class #' @description The Rcpp PolarVolume class #' A polar volume NULL #' @rdname RaveIO-class #' @name Rcpp_RaveIO-class #' @title Rcpp_RaveIO-class #' @description The Rcpp RaveIO class #' Used when loading and saving objects NULL #' @rdname Vol2BirdConfig-class #' @name Rcpp_Vol2BirdConfig-class #' @title Rcpp_Vol2BirdConfig-class #' @description The Rcpp vol2bird configuration class. #' Configuration instance used when processing data. NULL #' @rdname Vol2Bird-class #' @name Rcpp_Vol2Bird-class #' @title Rcpp_Vol2Bird-class #' @description The Rcpp vol2bird processing class. NULL #' Sets the main thread id #' #' @keywords internal cpp_vol2bird_namespace__store_main_thread_id <- function() { invisible(.Call(`_vol2birdR_cpp_vol2bird_namespace__store_main_thread_id`)) } #' Initializes the vol2birdR library #' #' @keywords internal cpp_vol2bird_initialize <- function() { invisible(.Call(`_vol2birdR_cpp_vol2bird_initialize`)) } #' Sets the wsr88d site location file #' #' @param loc location of file #' @keywords internal cpp_vol2bird_set_wsr88d_site_location <- function(loc) { invisible(.Call(`_vol2birdR_cpp_vol2bird_set_wsr88d_site_location`, loc)) } #' Returns the wsr88d site location file #' #' @return location of site location file #' @keywords internal cpp_vol2bird_get_wsr88d_site_location <- function() { .Call(`_vol2birdR_cpp_vol2bird_get_wsr88d_site_location`) } #' Initializes the mistnet shared library pointed to by the path #' #' @keywords internal cpp_vol2bird_version <- function() { .Call(`_vol2birdR_cpp_vol2bird_version`) } #' Initializes the mistnet shared library pointed to by the path #' #' @keywords internal #' @param path The shared library cpp_mistnet_init <- function(path) { invisible(.Call(`_vol2birdR_cpp_mistnet_init`, path)) } #' The software has to be compiled with -DRAVE_MEMORY_DEBUG and without -DNO_RAVE_PRINTF. #' Manual handling for now. #' @keywords internal cpp_printMemory <- function() { invisible(.Call(`_vol2birdR_cpp_printMemory`)) }
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/RcppExports.R
#' The default branch #' @keywords internal branch <- "main" supported_pytorch_versions=c("1.10.2", "1.12.1") #' Contains a list of 'MistNet' libraries for the various OS's #' @keywords internal install_config <- list( "1.12.1" = list( # Future version is 1.12.1. Need it to build for macOS ARM "cpu" = list( "darwin" = list( "libtorch" = list( url = "https://download.pytorch.org/libtorch/cpu/libtorch-macos-1.12.1.zip", path = "libtorch/", filter = ".dylib", md5hash = "bc05ee56d9134e5a36b97b949adf956a" ), "libmistnet" = sprintf("https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/%s/latest/macOS-cpu.zip", branch) ), "darwin-arm64" = list( "libtorch" = list( url = "https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/main/latest/libtorch-macos-arm64-volbird-1.12.1.zip", path = "libtorch/", filter = ".dylib", md5hash = "d2779f95bcd5527da3233382e45f6e3f" ), "libmistnet" = sprintf("https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/%s/latest/macOS-arm64-cpu.zip", branch) ), "windows" = list( "libtorch" = list( url = "https://download.pytorch.org/libtorch/cpu/libtorch-win-shared-with-deps-1.12.1%2Bcpu.zip", path = "libtorch/", filter = ".dll", md5hash = "18f46c55560cefe628f8c57b324a0a5c" ), "libmistnet" = sprintf("https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/%s/latest/Windows-cpu.zip", branch) ), "linux" = list( "libtorch" = list( path = "libtorch/", url = "https://download.pytorch.org/libtorch/cpu/libtorch-cxx11-abi-shared-with-deps-1.12.1%2Bcpu.zip", md5hash = "cfbc46b318c1e94efa359a98d4047ec8" ), "libmistnet" = sprintf("https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/%s/latest/Linux-cpu.zip", branch) ) ) ), "1.10.2" = list( "cpu" = list( "darwin" = list( "libtorch" = list( url = "https://download.pytorch.org/libtorch/cpu/libtorch-macos-1.10.2.zip", path = "libtorch/", filter = ".dylib", md5hash = "96ebbf1e2e44f30ee80bf3c8e4a31e15" ), "libmistnet" = sprintf("https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/%s/latest/macOS-cpu_1_10_2.zip", branch) ), "darwin-arm64" = list( "libtorch" = list( url = "https://download.pytorch.org/libtorch/cpu/libtorch-macos-1.10.2.zip", path = "libtorch/", filter = ".dylib", md5hash = "96ebbf1e2e44f30ee80bf3c8e4a31e15" ), "libmistnet" = sprintf("https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/%s/latest/macOS-arm64-cpu_1_10_2.zip", branch) ), "windows" = list( "libtorch" = list( url = "https://download.pytorch.org/libtorch/cpu/libtorch-win-shared-with-deps-1.10.2%2Bcpu.zip", path = "libtorch/", filter = ".dll", md5hash = "c49ddfd07ba65e0ff4a54e041ed22c42" ), "libmistnet" = sprintf("https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/%s/latest/Windows-cpu_1_10_2.zip", branch) ), "linux" = list( "libtorch" = list( path = "libtorch/", url = "https://download.pytorch.org/libtorch/cpu/libtorch-cxx11-abi-shared-with-deps-1.10.2%2Bcpu.zip", md5hash = "99d16043865716f5e38a8d15480b61c6" ), "libmistnet" = sprintf("https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/%s/latest/Linux-cpu_1_10_2.zip", branch) ) ) ) ) #' Returns the path of the 'MistNet' libraries for specified version #' @param version The 'MistNet' version checked for #' @return the path to the libraries #' @keywords internal install_path <- function(version = "1.0") { path <- Sys.getenv("MISTNET_HOME") if (nzchar(path)) { normalizePath(path, mustWork = FALSE) } else { normalizePath(file.path(system.file("", package = "vol2birdR")), mustWork = FALSE) } } #' Returns the 'LibTorch' installation path. #' #' Returns the directory where the LibTorch library has been downloaded #' @export #' #' @return a character path #' #' @examples #' torch_install_path() torch_install_path <- function() { install_path() } #' Checks if the 'LibTorch' and 'MistNet' libraries have been installed or not. #' @return TRUE if both 'LibTorch' and 'MistNet' libraries can be found, otherwise FALSE #' @export mistnet_exists <- function() { if (!dir.exists(install_path())) { return(FALSE) } if (!length(list.files(file.path(install_path(), "lib"), "torch")) > 0) { return(FALSE) } if (!length(list.files(file.path(install_path(), "lib"), "mistnet")) > 0) { return(FALSE) } TRUE } #' Returns the path of the 'MistNet' libraries for specified version #' @param library_name The name of the library searched for, either 'libmistnet' or 'LibTorch' #' @param install_path The location where to look for the libraries #' @return if anything could be located or not #' @keywords internal lib_installed <- function(library_name, install_path) { x <- list.files(file.path(install_path, "lib")) if (library_name == "libmistnet") { any(grepl("mistnet", x)) } else if (library_name == "libtorch") { any(grepl("torch", x)) } } #' Installs the library #' @param library_name The name of the library searched for, either 'libmistnet' or 'libtorch' #' @param library_url Where to fetch the library #' @param install_path Where to put the library #' @param source_path If library should be fetched from somewhere else #' @param filter Not used #' @param md5hash MD5 check #' @param inst_path inst path #' @keywords internal #' @return if anything could be located or not mistnet_install_lib <- function(library_name, library_url, install_path, source_path, filter, md5hash, inst_path) { library_extension <- paste0(".", tools::file_ext(library_url)) temp_file <- tempfile(fileext = library_extension) temp_path <- tempfile() utils::download.file(library_url, temp_file, mode="wb") on.exit(try(unlink(temp_file))) if (!is.null(md5hash) && is.character(md5hash) && length(md5hash) == 1) { hash <- tools::md5sum(temp_file) if (hash != md5hash) { stop( "The file downloaded from '", library_url, "' does not match the expected md5 hash '", md5hash, "'. The observed hash is '", hash, "'. Due to security reasons the installation is stopped." ) } } uncompress <- if (identical(library_extension, "tgz")) utils::untar else utils::unzip uncompress(temp_file, exdir = temp_path) #if (!file.exists(file.path(install_path, inst_path))){ # dir.create(file.path(install_path, inst_path)) #} file.copy( from = dir(file.path(temp_path, source_path), full.names = TRUE), to = file.path(install_path, inst_path), recursive = TRUE ) } #' Returns the system name #' @keywords internal install_os <- function() { tolower(Sys.info()[["sysname"]]) } #' Installs the 'MistNet' libraries #' @param version version to install #' @param type what type of libraries to be installed #' @param install_path Where libraries should be installed #' @param install_config the library config #' @keywords internal mistnet_install_libs <- function(version, type, install_path, install_config) { current_os <- install_os() if (!version %in% names(install_config)) { stop( "Version ", version, " is not available, available versions: ", paste(names(install_config), collapse = ", ") ) } if (!type %in% names(install_config[[version]])) { stop("The ", type, " installation type is currently unsupported.") } if (current_os == "darwin") { if (tolower(Sys.info()[["machine"]]) == "arm64") { current_os <- "darwin-arm64" } } if (!current_os %in% names(install_config[[version]][[type]])) { stop("The ", current_os, " operating system is currently unsupported.") } install_info <- install_config[[version]][[type]][[current_os]] for (library_name in names(install_info)) { if (lib_installed(library_name, install_path)) { next } library_info <- install_info[[library_name]] if (!is.list(library_info)) { library_info <- list(url = library_info, filter = "", path = "", inst_path = "lib") } if (is.null(library_info$filter)) library_info$filter <- "" if (is.null(library_info$inst_path)) library_info$inst_path <- "" mistnet_install_lib( library_name = library_name, library_url = library_info$url, install_path = install_path, source_path = library_info$path, filter = function(e) grepl(library_info$filter, e), md5hash = library_info$md5hash, inst_path = library_info$inst_path ) } invisible(install_path) } #' Returns the LibTorch install type #' @keywords internal install_type <- function(version) { return("cpu") } #' Install 'MistNet' model file #' #' Installs the 'MistNet' model file in 'PyTorch' format #' #' @param reinstall Re-install the model even if its already installed #' @param path Optional path to install or check for an already existing installation. #' @param timeout Optional timeout in seconds for large file download. #' @param from_url From where the 'MistNet' model file should be downloaded. #' @param method The download method to use, see \link[utils]{download.file} #' @param ... other optional arguments (like \code{`load`} for manual installation). #' #' @return No value returned, this function downloads a file #' #' @details #' Download and install the 'MistNet' model file. By default the library is downloaded to #' data/mistnet_nexrad.pt in the 'vol2birdR' package directory. #' #' Alternatively, the model file can be downloaded to a different location, which has the #' advantage that it doesn't have to be redownloaded after a reinstall of 'vol2birdR'. #' #' 'vol2birdR' will automatically detect the model file if it is downloaded to #' `/opt/vol2bird/etc/mistnet_nexrad.pt`, which can be done as follows #' ```R #' install_mistnet_model(path="/opt/vol2bird/etc/mistnet_nexrad.pt") #' ``` #' @examples #' \donttest{ #' install_mistnet_model() #' } #' #' @export install_mistnet_model <- function(reinstall=FALSE, path = file.path(torch_install_path(),"data","mistnet_nexrad.pt"), timeout = 1800, from_url="http://mistnet.s3.amazonaws.com/mistnet_nexrad.pt", method="libcurl", ...) { if (!dir.exists(dirname(path))) { if(!dir.create(dirname(path), recursive=TRUE)){ stop("cannot create directory") } } if (reinstall) { if (file.exists(path)) { unlink(path) } } if (file.exists(path)) { return(TRUE) } temp_file <- tempfile(fileext = ".pt") withr::with_options( list(timeout = timeout), utils::download.file(from_url, temp_file, method=method, mode="wb") ) on.exit(try(unlink(temp_file))) file.copy( from = temp_file, to = path ) return(TRUE) } #' Install 'MistNet' libraries #' #' Installs libraries and dependencies for using 'MistNet'. #' #' @param version The 'LibTorch' version to install. #' @param reinstall Re-install 'MistNet' even if its already installed? #' @param path Optional path to install or check for an already existing installation. #' @param timeout Optional timeout in seconds for large file download. #' @param ... other optional arguments (like \code{`load`} for manual installation). #' #' @return no value returned. Installs libraries into the package #' #' @details #' By default libraries are installed in the 'vol2birdR' package directory. #' #' When using \code{path} to install in a specific location, make sure the \code{MISTNET_HOME} environment #' variable is set to this same path to reuse this installation. #' #' The \code{TORCH_INSTALL} environment #' variable can be set to \code{0} to prevent auto-installing 'LibTorch and \code{TORCH_LOAD} set to \code{0} #' to avoid loading dependencies automatically. These environment variables are meant for advanced use #' cases and troubleshooting only. #' #' When timeout error occurs during library archive download, or length of downloaded files differ from #' reported length, an increase of the \code{timeout} value should help. #' #' @export #' #' @examples #' \donttest{ #' install_mistnet() #' } #' #' @seealso #' * [install_mistnet_from_file()] install_mistnet <- function(version = "1.12.1", reinstall = FALSE, path = install_path(), timeout = 360, ...) { cat("Starting installation of MistNet...\n") assert_that(version %in% supported_pytorch_versions, msg = paste("version should be",paste(supported_pytorch_versions, collapse = " or "))) assert_that(is.flag(reinstall)) assert_that(is.number(timeout)) if (reinstall) { cat("Reinstall flag set. Unlinking the existing path...\n") unlink(path, recursive = TRUE) } if (!dir.exists(path)) { cat("Creating directory for MistNet installation...\n") ok <- dir.create(path, showWarnings = FALSE, recursive = TRUE) if (!ok) { rlang::abort(c("Failed creating directory", paste("Check that you can write to: ", path))) } } # check for write permission cat("Checking write permissions...\n") if (file.access(path, 2) < 0) { rlang::abort(c("No write permissions to install mistnet.", paste("Check that you can write to:", path), "Or set the MISTNET_HOME env var to a path with write permissions.")) } if (!is.null(list(...)$install_config) && is.list(list(...)$install_config)) { install_config <- list(...)$install_config } cat("Installing MistNet libraries...\n") withr::with_options(list(timeout = timeout), mistnet_install_libs(version, "cpu", path, install_config)) cat("Initializing MistNet...\n") if (!identical(list(...)$load, FALSE)) { mistnet_start(reload = TRUE) cat("MistNet initialized successfully.\n") } cat("MistNet installation complete.\n") } #' Install 'MistNet' libraries from files #' #' Installs 'LibTorch' and 'MistNet' dependencies from files. #' #' @param version The 'LibTorch' version to install. #' @param libtorch The installation archive file to use for 'LibTorch'. Shall be a \code{"file://"} URL scheme. #' @param libmistnet The installation archive file to use for 'MistNet'. Shall be a \code{"file://"} URL scheme. #' @param mistnet_model The installation archive file to use for the model. Shall be a \code{"file://"} URL scheme. Is optional! #' @param ... other parameters to be passed to `install_torch()` #' #' @return a list with character urls #' #' @details #' #' When [install_mistnet()] initiated download is not possible, but installation archive files are #' present on local filesystem, [install_mistnet_from_file()] can be used as a workaround to installation issues. #' \code{"libtorch"} is the archive containing all 'LibTorch' modules, and \code{"libmistnet"} is the 'C' interface to 'LibTorch' #' that is used for the 'R' package. Both are highly platform dependent, and should be checked through [get_install_urls()] #' #' ```R #' > get_install_urls() #' $libtorch #' [1] "https://download.pytorch.org/libtorch/cpu/libtorch-cxx11-abi-shared-with-deps-1.10.2%2Bcpu.zip" #' #' $libmistnet #' [1] "https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/main/latest/Linux-cpu.zip" #' #' $mistnet_model #' [1] "http://mistnet.s3.amazonaws.com/mistnet_nexrad.pt" #' ``` #' #' In a terminal, download above zip-files. #' ```R #' %> mkdir /tmp/myfiles #' %> cd /tmp/myfiles #' %> wget https://download.pytorch.org/libtorch/cpu/libtorch-cxx11-abi-shared-with-deps-1.10.2%2Bcpu.zip #' %> wget https://s3.amazonaws.com/vol2bird-builds/vol2birdr/refs/heads/main/latest/Linux-cpu.zip #' %> wget http://mistnet.s3.amazonaws.com/mistnet_nexrad.pt #' ``` #' Then in R, type: #' ```R #' > install_mistnet_from_file(libtorch="file:///tmp/myfiles/libtorch-cxx11-abi-shared-with-deps-1.10.2+cpu.zip", #' libmistnet="file:///tmp/myfiles/Linux-cpu.zip", #' mistnet_model="file:///tmp/myfiles/mistnet_nexrad.pt") #' ``` #' @export #' #' @examples #' # get paths to files to be downloaded #' get_install_urls() #' # download the files to a directory on disk, e.g. to /tmp/myfile, #' # then install with: #' \dontrun{ #' install_mistnet_from_file( #' libtorch="file:///tmp/myfiles/libtorch-cxx11-abi-shared-with-deps-1.10.2+cpu.zip", #' libmistnet="file:///tmp/myfiles/Linux-cpu.zip", #' mistnet_model="file:///tmp/myfiles/mistnet_nexrad.pt") #' } #' #' @seealso #' * [install_mistnet()] install_mistnet_from_file <- function(version = "1.12.1", libtorch, libmistnet, mistnet_model=NULL, ...) { assert_that(version %in% supported_pytorch_versions, msg = paste("version should be",paste(supported_pytorch_versions, collapse = " or "))) assert_that(inherits(url(libtorch), "file")) assert_that(inherits(url(libmistnet), "file")) install_config[[version]][["cpu"]][[install_os()]][["libtorch"]][["url"]] <- libtorch install_config[[version]][["cpu"]][[install_os()]][["libmistnet"]] <- libmistnet install_mistnet(version = version, type = "cpu", install_config = install_config, ...) if (!is.null(mistnet_model)) { install_mistnet_model(from_url=mistnet_model) } } #' List of installation files to download #' #' List the 'LibTorch' and 'MistNet' files to download as local files #' in order to proceed with [install_mistnet_from_file()]. #' #' @param version The 'LibTorch' version to install. #' @param type The installation type for 'LibTorch'. Valid value is currently \code{"cpu"}. #' #' @export #' #' @return a named list with character urls #' #' @seealso #' * [install_mistnet_from_file()] get_install_urls <- function(version = "1.10.2", type = install_type(version = version)) { assert_that(version %in% supported_pytorch_versions) libtorch <- install_config[[version]][[type]][[install_os()]][["libtorch"]][["url"]] libmistnet <- install_config[[version]][[type]][[install_os()]][["libmistnet"]] mistnet_model <- "http://mistnet.s3.amazonaws.com/mistnet_nexrad.pt" list(libtorch = libtorch, libmistnet = libmistnet, mistnet_model = mistnet_model) }
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/install.R
#' Loads a volume vol2bird-style meaning that a number of different file formats #' are tried and eventually loaded. #' @param file name of file to be loaded #' @return The loaded volume as a Rcpp_PolarVolume that can be passed around #' @keywords internal load_volume <- function(file){ processor<-Vol2Bird$new() vol<-processor$load_volume(file) return(vol) }
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/load_volume.R
.globals <- new.env(parent = emptyenv()) .globals$mistnet_started <- FALSE #' The default 'MistNet' version #' @return the default 'MistNet' version #' @keywords internal mistnet_default <- function() { "1.0.0" } #' Initialize the 'MistNet' system if enabled. #' @param version version of 'MistNet' library #' @param reload if 'MistNet' library should be reloaded or not, default FALSE. #' @keywords internal mistnet_start <- function(version = mistnet_default(), reload = FALSE) { if (!mistnet_exists()) { stop("'MistNet' is disabled.") } if (.globals$mistnet_started && !reload) { return() } # Path where the DLL should be dll_path <- file.path(install_path(), "lib") cat("Attempting to load MistNet from:", dll_path, "\n") # Try-catch block to capture any errors during initialization tryCatch({ cpp_mistnet_init(dll_path) .globals$mistnet_started <- TRUE cat("MistNet successfully initialized.\n") }, error = function(e) { cat("Error during MistNet initialization: ", e$message, "\n") }, warning = function(w) { cat("Warning during MistNet initialization: ", w$message, "\n") }) }
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/mistnet_load.R
#' Retrieve or set the nexrad location file #' #' Retrieves and sets the path of the RSL nexrad location file #' @details The RSL library stores the locations and names of NEXRAD stations in a fixed-width #' text file. This function retrieves the path of the location file, and allows one to set #' the path to a different location file. #' #' @param file A string containing the path of a location file. Do not specify to retrieve path of current location file. #' @return The path of the nexrad location file #' @examples #' # return current location file #' nexrad_station_file() #' # store nexrad station file path #' file_path <- nexrad_station_file() #' # set station location file #' nexrad_station_file(file_path) #' #' @export nexrad_station_file <- function(file){ if(missing(file)){ return(cpp_vol2bird_get_wsr88d_site_location()) } assert_that(file.exists(file)) data=tryCatch(utils::read.delim(file),error=function(e) NULL) assert_that(is.data.frame(data),msg=paste0("file '",file,"' is not a fixed-width data table")) assert_that(ncol(data)==11,msg=sprintf("expecting a file with 11 columns, found %i",ncol(data))) cpp_vol2bird_set_wsr88d_site_location(file) return(file) }
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/nexrad_station_file.R
globalVariables(c("..", "self", "private", "N")) .generator_null <- NULL .compilation_unit <- NULL .onAttach <- function(libname, pkgname) { } .onLoad <- function(libname, pkgname) { # required environment variable on Mac for parallel use of libtorch: osname<-tolower(Sys.info()[["sysname"]]) if (osname == "darwin" && Sys.getenv("OMP_NUM_THREADS") == "") { Sys.setenv(OMP_NUM_THREADS = parallel::detectCores()) } cpp_vol2bird_namespace__store_main_thread_id() cpp_vol2bird_initialize() cpp_vol2bird_set_wsr88d_site_location(file.path(find.package(pkgname), "librsl", "wsr88d_locations.dat")) install_success <- TRUE if (mistnet_exists() && install_success) { # in case init fails we will just have disabled mistnet and run without it.. tryCatch( { mistnet_start() }, error = function(e) { } ) } } .onUnload <- function(libpath) { }
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/package.R
# Function to check file existence and permissions check_file_access <- function(file_path) { if (!file.exists(file_path)) { cat("Error: File does not exist:", file_path, "\n") return(FALSE) } if (!file.access(file_path, 4) == 0) { cat("Error: No read permission for the file:", file_path, "\n") return(FALSE) } file_info <- file.info(file_path) cat("File size:", file_info$size, "bytes\n") # Add more checks here if necessary, e.g., file checksum return(TRUE) } #' Convert a NEXRAD polar volume file to an ODIM polar volume file #' #' @inheritParams vol2bird #' #' @return No value returned, creates a file specified by `pvolfile_out` argument. #' #' @seealso #' * [vol2bird_config()] #' @export #' #' @examples #' \donttest{ #' # define filenames #' nexrad_file <- paste0(tempdir(),"/KBGM20221001_000243_V06") #' odim_file <- paste0(tempdir(),"/KBGM20221001_000243_V06.h5") #' # download NEXRAD file: #' download.file("https://noaa-nexrad-level2.s3.amazonaws.com/2022/10/01/KBGM/KBGM20221001_000243_V06", #' destfile = nexrad_file, mode="wb") #' # convert NEXRAD file to ODIM hdf5 format: #' rsl2odim(nexrad_file, pvolfile_out = odim_file) #' # clean up #' file.remove(nexrad_file) #' file.remove(odim_file) #' } rsl2odim <- function(file, config, pvolfile_out="", verbose=TRUE, update_config=FALSE){ for (filename in file) { assert_that(file.exists(filename)) cat("Checking file before processing:", filename, "\n") if (!file.exists(filename)) { stop("Error: File does not exist: ", filename) } if (!check_file_access(filename)) { stop("File access check failed for: ", filename) } } if (!are_equal(pvolfile_out, "")) { assert_that(is.writeable(dirname(pvolfile_out))) } if(missing(config)){ config <- vol2bird_config() } assert_that(is.flag(verbose)) assert_that(is.flag(update_config)) if(config$useMistNet){ assert_that(mistnet_exists(),msg="mistnet installation not found, install with `install_mistnet()`") assert_that(file.exists(config$mistNetPath),msg="mistnet model file not found, point `mistNetPath` option to valid mistnet file or download the model with `install_mistnet_model()`") } assert_that(inherits(config,"Rcpp_Vol2BirdConfig")) # make a copy of the configuration object for parallel processes. # The processor might change the configuration object based on the # input file characteristics if(update_config){ config_instance <- config } else{ config_instance <- vol2bird_config(config) } processor<-Vol2Bird$new() processor$verbose <- verbose processor$rsl2odim(path.expand(file), config_instance, path.expand(pvolfile_out)) }
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/rsl2odim.R
#' Calculate a vertical profile (`vp`) from a polar volume (`pvol`) file #' #' Calculates a vertical profile of biological scatterers (`vp`) from a polar #' volume (`pvol`) file using the algorithm #' [vol2bird](https://github.com/adokter/vol2bird/) (Dokter et al. #' 2011 \doi{10.1098/rsif.2010.0116}). #' #' @param file Character (vector). Either a path to a single radar polar volume #' (`pvol`) file containing multiple scans/sweeps, or multiple paths to scan #' files containing a single scan/sweep. The file data format should be either 1) #' [ODIM](https://github.com/adokter/vol2bird/blob/master/doc/OPERA2014_O4_ODIM_H5-v2.2.pdf) #' format, which is the implementation of the OPERA data information model in #' the [HDF5](https://support.hdfgroup.org/HDF5/) format, 2) NEXRAD format #' supported by the ['RSL' #' library](https://trmm-fc.gsfc.nasa.gov/trmm_gv/software/rsl/) or 3) Vaisala #' IRIS (IRIS RAW) format. IRIS format is not available on CRAN, see #' vol2birdR development version on Github. #' @param config optional configuration object of class `Rcpp_Vol2BirdConfig`, #' typically output from \link{vol2bird_config} #' @param vpfile Character. File name. When provided with .csv extension, writes a vertical profile #' time series (vpts) in the [standard CSV format](https://aloftdata.eu/vpts-csv/). Proivded with another or no exentsion, #' writes a vertical profile vertical profile file (`vpfile`) in the ODIM HDF5 format to disk. #' @param pvolfile_out Character. File name. When provided, writes a polar #' volume (`pvol`) file in the ODIM HDF5 format to disk. Useful for converting #' 'RSL' formats to ODIM, and for adding 'MistNet' segmentation output. #' @param verbose logical. When TRUE print profile output to console. #' @param update_config logical. When TRUE processing options that are determined based on #' input file characteristics are returned and updated in the object specified by the `config` #' argument. Do not set to `TRUE` when `vol2bird()` is used in loops like `lapply()` or in parallel processes. #' #' @return No value returned, creates a file specified by `file` argument #' #' @examples #' # Locate the polar volume example file #' pvolfile <- system.file("extdata", "volume.h5", package = "vol2birdR") #' #' # Create a configuration instance: #' conf <- vol2bird_config() #' #' # Define output file #' output_file <- paste0(tempdir(), "/vp.h5") #' #' # Calculate the profile: #' vol2bird(file = pvolfile, config = conf, vpfile = output_file) #' #' @seealso #' * [vol2bird_config()] #' @export vol2bird <- function(file, config, vpfile="", pvolfile_out="", verbose=TRUE, update_config=FALSE){ for (filename in file) { assert_that(file.exists(filename)) } if (!are_equal(vpfile, "")) { assert_that(is.writeable(dirname(vpfile))) } if(missing(config)){ config <- vol2bird_config() } assert_that(is.flag(verbose)) assert_that(is.flag(update_config)) assert_that(inherits(config,"Rcpp_Vol2BirdConfig")) if(config$useMistNet){ assert_that(mistnet_exists(),msg="'MistNet' installation not found, install with `install_mistnet()`") assert_that(file.exists(config$mistNetPath),msg="'MistNet' model file not found, point `mistNetPath` option to valid 'MistNet' file or download the model with `install_mistnet_model()`") } # make a copy of the configuration object for parallel processes. # The processor might change the configuration object based on the # input file characteristics if(update_config){ config_instance <- config } else{ config_instance <- vol2bird_config(config) } processor<-Vol2Bird$new() processor$verbose <- verbose processor$process(path.expand(file), config_instance, path.expand(vpfile), path.expand(pvolfile_out)) }
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/vol2bird.R
#' @details #' To get started, see: #' #' \itemize{ #' \item Dokter et al. (2016) \doi{https://doi.org/10.1098/rsif.2010.0116}: a #' paper describing the profiling algorithm. #' \item \href{https://adriaandokter.com/vol2bird/}{'vol2bird' 'C' code documentation}: #' an overview of the algorithm structure. #' \item Lin T-Y et al. (2019) \doi{https://doi.org/10.1111/2041-210X.13280}: a #' paper describing the 'MistNet' model for rain segmentation. #' } #' #' @keywords internal #' #' @import methods #' @useDynLib vol2birdR, .registration = TRUE #' @import assertthat #' @import pkgbuild #' @importFrom utils str #' @importFrom rlang abort #' @importFrom utils capture.output #' @import Rcpp "_PACKAGE" loadModule("RaveIO",TRUE) loadModule("PolarVolume",TRUE) loadModule("Vol2Bird",TRUE) loadModule("Vol2BirdConfig",TRUE)
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/vol2birdR.R
#' Create a 'vol2bird' configuration instance #' #' Creates or copies a 'vol2bird' configuration instance of class `Rcpp_Vol2BirdConfig` #' #' @param config a configuration instance to be copied. #' #' @return an object of class `Rcpp_Vol2BirdConfig` #' #' @details #' ## Copying configuration instances #' All processing options for [vol2bird()] are set using a configuration instance of class `Rcpp_Vol2BirdConfig` #' In some cases it might be necessary to copy and modify configuration instance, for example #' when processing polar volume files with different settings. #' In these cases you can't copy the instance like: #' ```R #' config<-vol2bird_config() #' extra_config<-config #' ``` #' In the above example, the `config` and `extra_config` instances will both refer to the same object. #' (copy by reference). To avoid this (and make a copy by value), use: #' ```R #' config<-vol2bird_config() #' # create a copy identical to object config: #' extra_config<-vol2bird_config(config) #' ``` #' #' ## User configuration options #' The `Rcpp_Vol2BirdConfig` class object sets the following 'vol2bird' processing options: #' * `azimMax`: Numeric. The minimum azimuth (0-360 degrees) used for constructing the bird density profile #' * `azimMin`: Numeric. The maximum azimuth (0-360 degrees) used for constructing the bird density profile #' * `birdRadarCrossSection`: Numeric. Radar cross section in cm^2 #' * `clutterMap`: Character. clutter map path and filename #' * `clutterValueMin`: Numeric. sample volumes in the static cluttermap with a value above #' this threshold will be considered clutter-contaminated. Default 0.1 #' * `dbzType`: Character. Reflectivity factor quantity to use. Default `DBZH` #' * `dualPol`: Logical. Whether to use dual-pol moments for filtering meteorological echoes. Default `TRUE` #' * `elevMax`: Numeric. The minimum scan elevation in degrees used for constructing the bird density profile #' * `elevMin`: Numeric. The maximum scan elevation in degrees used for constructing the bird density profile #' * `layerThickness`: Numeric. The width/thickness of an altitude layer in m. Default 200 #' * `mistNetPath`: Character. Path of 'MistNet' segmentation model in pytorch (.pt) format #' * `nLayers`: Integer. The number of layers in an altitude profile. Default 25 #' * `radarWavelength`: Numeric. The radar wavelength in cm to assume when unavailable as an attribute in the input file. Default 5.3 #' * `rangeMax`: Numeric. The maximum range in m used for constructing the bird density profile. Default 35000 #' * `rangeMin`: Numeric. The minimum range in m used for constructing the bird density profile. Default 5000 #' * `rhohvThresMin`: Numeric. Correlation coefficients higher than this threshold will be classified as precipitation. Default 0.95 #' * `singlePol`: Logical. Whether to use single-pol moments for filtering meteorological echoes. Default `TRUE` #' * `stdDevMinBird`: Numeric. VVP Radial velocity standard deviation threshold. Default 2 m/s. #' * `useClutterMap`: Logical. Whether to use a static clutter map. Default `FALSE` #' * `useMistNet`: Logical. Whether to use the 'MistNet' segmentation model. Default `FALSE`. #' #' ## Advanced configuration options #' Changing these settings is rarely needed. #' * `cellEtaMin`: Numeric. Maximum mean reflectivity in cm^2/km^3 for cells containing birds #' * `cellStdDevMax`: Numeric. When analyzing precipitation cells, only cells for which the stddev of #' vrad (aka the texture) is less than cellStdDevMax are considered in the rest of the analysis #' * `dbzThresMin`: Numeric. Minimum reflectivity factor of a gate to be considered for inclusion in a weather cell. Default 0 dBZ #' * `dealiasRecycle`: Logical. Whether we should dealias all data once (default `TRUE`), or dealias for each profile individually (`FALSE`) #' * `dealiasVrad`: Logical. Whether we should dealias the radial velocities. Default `TRUE`. #' * `etaMax`: Numeric. Maximum reflectivity in cm^2/km^3 for single gates containing birds. Default 36000 #' * `exportBirdProfileAsJSONVar`: Logical. Deprecated, do not use. Default `FALSE` #' * `fitVrad`: Logical. Whether or not to fit a model to the observed vrad. Default `TRUE` #' * `maxNyquistDealias`: Numeric. When all scans have nyquist velocity higher than this value, dealiasing is suppressed. Default 25 m/s. #' * `minNyquist`: Numeric. Scans with Nyquist velocity lower than this value are excluded. Default 5 m/s. #' * `mistNetElevs`: Numeric vector of length 5. Elevations to use in Cartesian projection for 'MistNet'. Default `c(0.5, 1.5, 2.5, 3.5, 4.5)` #' * `mistNetElevsOnly`: Logical. When `TRUE` (default), use only the specified elevation scans for 'MistNet' to calculate profile, otherwise use all available elevation scans #' * `requireVrad`: Logical. For a range gate to contribute it should have a valid radial velocity. Default `FALSE` #' * `resample`: Logical. Whether to resample the input polar volume. Downsampling speeds up the calculation. Default `FALSE` #' * `resampleNbins`: Numeric. Resampled number of range bins. Ignored when `resample` is `FALSE`. Default 100 #' * `resampleNrays`: Numeric. Resampled number of azimuth bins. Ignored when `resample` is `FALSE`. Default 360 #' * `resampleRscale`: Numeric. Resampled range gate length in m. Ignored when `resample` is `FALSE`. Default 500 m. #' ## Algorithm constants #' Changing any of these constants is not recommended #' * `constant_absVDifMax`: Numeric. After fitting the radial velocity data, throw out any VRAD observations that #' are more than absVDifMax away from the fitted value as outliers. Default 10 #' * `constant_areaCellMin`: Numeric. When analyzing cells, areaCellMin determines the minimum size #' of a cell to be considered in the rest of the analysis. in km^2. Default 0.5 #' * `constant_cellClutterFractionMax`: Cells with clutter fractions above this value are likely not birds. Default 0.5 #' * `constant_chisqMin`: Minimum standard deviation of the VVP fit. Default 1e-05 #' * `constant_fringeDist`: Each identified weather cell is grown by a distance equal to 'fringeDist' using a region-growing approach. Default 5000 #' * `constant_nAzimNeighborhood`: vrad's texture is calculated based on the local neighborhood. The neighborhood size in the azimuth direction is equal to this value. Default 3 #' * `constant_nBinsGap`: When determining whether there are enough vrad observations in each direction, use nBinsGap sectors. Default 8 #' * `constant_nCountMin`: The minimum number of neighbors for the texture value to be considered valid, as used in calcTexture(). Default 4 #' * `constant_nNeighborsMin`: the minimum number of direct neighbors with dbz value above dbzThresMin as used in findWeatherCells(). Default 5 #' * `constant_nObsGapMin`: there should be at least this many vrad observations in each sector. Default 5 #' * `constant_nPointsIncludedMin`: when calculating the altitude-layer averaged dbz, there should be at least this many valid data points. Default 25 #' * `constant_nRangNeighborhood`: vrad's texture is calculated based on the local neighborhood. The neighborhood size in the range direction is equal to this value. Default 3 #' * `constant_refracIndex`: Refractive index of the scatterers. Default equal to water 0.964 #' * `constant_vradMin`: When analyzing cells, radial velocities lower than vradMin are treated as clutter. Default 1 m/s. #' #' ## Debug printing options #' Enable these printing options only for debugging purposes #' in a terminal, since large amounts of data will be dumped into the console. #' * `printCell`: Logical. Print precipitation cell data to stderr. Default `FALSE` #' * `printCellProp`: Logical. Print precipitation cell properties to stderr. Default `FALSE` #' * `printClut`: Logical. Print clutter data to stderr. Default `FALSE` #' * `printDbz`: Logical. Print reflectivity factor data to stderr. Default `FALSE` #' * `printDealias`: Logical. `FALSE` #' * `printOptions`: Logical. Print options to stderr. Default `FALSE` #' * `printPointsArray`: Logical. Print the 'points' array to stderr. Default `FALSE` #' * `printProfileVar`: Logical. Print profile data to stderr. Default `FALSE` #' * `printRhohv`: Logical. Print correlation coefficient data to stderr. Default `FALSE` #' * `printTex`: Logical. Print radial velocity texture data to stderr. Default `FALSE` #' * `printVrad`: Logical. Print radial velocity data to stderr. Default `FALSE` #' #' @export #' #' @seealso #' * [vol2bird()] #' #' @examples #' # create a configuration instance #' config <- vol2bird_config() #' # list the the configuration elements: #' config #' # change the maximum range included in the profile generation to 40 km: #' config$rangeMax <- 40000 #' # make a copy of the configuration instance: #' config_copy <- vol2bird_config(config) vol2bird_config <- function(config){ if(missing(config)){ output=Vol2BirdConfig$new() mistnet_model_path <- file.path(find.package("vol2birdR"), "data", "mistnet_nexrad.pt") if(file.exists(mistnet_model_path)){ output$mistNetPath <- mistnet_model_path } } else{ assert_that(inherits(config,"Rcpp_Vol2BirdConfig")) output=Vol2BirdConfig$new(config) } output } # change the default print method for Rcpp_Vol2BirdConfig class setMethod(f = "show", signature = "Rcpp_Vol2BirdConfig", definition = function(object){ str_capture <- capture.output(str(object)) # hide constant options str_capture <- str_capture[!grepl("constant_",str_capture)] # hide print options str_capture <- str_capture[!grepl("print",str_capture)] # remove first and last two lines of str output, and add header: cat(c("'vol2bird' configuration:",str_capture[2:(length(str_capture)-2)]),sep="\n") })
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/vol2bird_config.R
#' Return 'vol2bird' version #' #' Return version of the 'vol2bird' algorithm #' #' @return an object of class \link{numeric_version} #' #' @export #' @examples #' # check installed 'vol2bird' version: #' vol2bird_version() vol2bird_version <- function(){ numeric_version(cpp_vol2bird_version()) }
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/vol2bird_version.R
#' Skip test if tempdir() not accessible #' #' Some function tests require tempdir() to be writeable in package vol2birdR. #' This helper function allows to skip a test if tempdir() is not accessible #' Inspired by <https://testthat.r-lib.org/articles/skipping.html#helpers>. #' #' @keywords internal skip_if_no_temp_access <- function() { tmpdir <- tempdir() if (is.writeable(tmpdir) && is.readable(tmpdir)) { return(invisible(TRUE)) } testthat::skip("tempdir() not accessible") }
/scratch/gouwar.j/cran-all/cranData/vol2birdR/R/zzz.R
--- title: "Introduction to vol2birdR" author: Adriaan M. Dokter & Anders Henja output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to vol2birdR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- vol2birdR is an R package for calculating vertical profiles and other biological scatterers from weather radar data. The original **vol2bird** is written as a C-package and has been migrated to also work as an R package. ## Introduction The vol2birdR package provides necessary functions to process polar volume data of C-band and S-band radars into vertical profiles of biological scatterers. This package also enables libtorch and the MistNet model for segmentation of meteorological and biological signals. ## Calculating vertical profiles First, define a configuration instance, and modify configuration settings according to needs. ``` # load the library library(vol2birdR) # create a configuration instance config<-vol2bird_config() # modify the configuration instance as needed # in this example we set the maximum range to 25 km: config$rangeMax <- 25000 ``` The configuration object can be modified heavily. Learn more about the available options in the documentation of `vol2bird_config()` Note that configuration objects are copied by reference by default, and true copies that can be used independently should be assigned using: ``` config <- vol2bird_config() config_copy <- vol2bird_config(config) ``` Finally, the vertical profile can be calculated using function `vol2bird()`: ``` vol2bird(file="/your/input/pvolfile",config=config, vpfile="/your/output/vpfile") ``` The input pvolfile needs to be in ODIM HDF5 format, IRIS RAW format, or NEXRAD format. The output vpfile containing the profile will be in ODIM HDF5 format. ## MistNet ### Installation MistNet is a deep convolution neural net for segmenting out rain in S-band radar data, see the publication at https://besjournals.onlinelibrary.wiley.com/doi/full/10.1111/2041-210X.13280. To use MistNet, follow the following additional installation steps: After installing and loading vol2birdR, run `install_mistnet()` from R. This will download libtorch from the download section of https://pytorch.org as well as a wrapper library from AWS that enables the mistnet functionality: ``` # STEP 1: install mistnet libraries library(vol2birdR) install_mistnet() ``` After completing this step, the following command should evaluate to `TRUE`: ``` mistnet_exists() ``` Next, the pytorch mistnet model needs to be downloaded, which is hosted at http://mistnet.s3.amazonaws.com/mistnet_nexrad.pt. Note that this file is large, over 500Mb. It can be downloaded directly from R using `install_mistnet_model()`: ``` # STEP 2: download mistnet model: # install mistnet model into vol2birdR package: install_mistnet_model() ``` `install_mistnet_model()` installs the model by default into the vol2birdR package directory. As a result, when reinstalling vol2birdR the model file will have to be re-downloaded as well. Alternatively, you can store the model in an alternative location outside the vol2birdR package directory. This has the advantage that you don't have to re-download the model when reinstalling vol2birdR. Simply store the path of the mistnet_nexrad.pt file in the `mistNetPath` element of your configuration object (see `vol2bird_config()`) vol2birdR will automatically locate the file if it is located at `/opt/vol2bird/etc/mistnet_nexrad.pt`, which can be done as follows: ``` # create the directory # (in case of a permission-denied error, create the directory manually) dir.create("/opt/vol2bird/etc", recursive=TRUE) # download the model install_mistnet_model(path="/opt/vol2bird/etc/mistnet_nexrad.pt") ``` ### Using MistNet After installing the MistNet libraries and model file, a profile can be calculated as follows: ``` # define configuration object: config <- vol2bird_config() # enable MistNet: config$useMistNet <- TRUE # calculate the profile: vol2bird(file="/your/input/pvolfile", config=config, vpfile="/your/output/vpfile") ```
/scratch/gouwar.j/cran-all/cranData/vol2birdR/inst/doc/vol2birdR.Rmd
if (pkgbuild::has_rtools()) { ver<-pkgbuild::rtools_needed() CFLAGS<-"" if (ver != "Rtools 4.0") { CFLAGS<-"-DH5_USE_110_API" } cat(CFLAGS) quit("no", status=0) } quit("no", status=127)
/scratch/gouwar.j/cran-all/cranData/vol2birdR/tools/get_h5_api_cflags.R
if (pkgbuild::has_rtools()) { ver<-pkgbuild::rtools_needed() LIBS<-"-lhdf5 -lwsock32 -lz -lsz -lm -ldl -lws2_32" if (ver == "Rtools 4.0") { LIBS<-"-lhdf5 -lz" } cat(LIBS) quit("no", status=0) } quit("no", status=127)
/scratch/gouwar.j/cran-all/cranData/vol2birdR/tools/get_hdf5_libraries.R
if (pkgbuild::has_rtools()) { ver<-pkgbuild::rtools_needed() LIBS<-"-lproj -lsqlite3 -lz -ldl -ltiff -lwebp -lsharpyuv -lzstd -llzma -ljpeg -lz -lcurl -lidn2 -lunistring -liconv -lcharset -lssh2 -lgcrypt -lgpg-error -lws2_32 -lgcrypt -lgpg-error -lws2_32 -lz -ladvapi32 -lcrypt32 -lssl -lcrypto -lssl -lz -lws2_32 -lgdi32 -lcrypt32 -lcrypto -lbcrypt -lz -lws2_32 -lgdi32 -lcrypt32 -lgdi32 -lwldap32 -lzstd -lz -lws2_32 -lpthread -lstdc++" if (ver == "Rtools 4.0") { LIBS<-"-lproj -lsqlite3 -lz -ltiff -ljpeg -lz -lcurl -lnormaliz -lssh2 -lcrypt32 -lgdi32 -lws2_32 -lcrypt32 -lgdi32 -lws2_32 -lssl -lcrypto -lws2_32 -lgdi32 -lcrypt32 -lz -lssl -lcrypto -lssl -lcrypto -lws2_32 -lgdi32 -lcrypt32 -lgdi32 -lcrypt32 -lwldap32 -lz -lws2_32 -lstdc++" } cat(LIBS) quit("no", status=0) } quit("no", status=127)
/scratch/gouwar.j/cran-all/cranData/vol2birdR/tools/get_proj_libraries.R
--- title: "Introduction to vol2birdR" author: Adriaan M. Dokter & Anders Henja output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to vol2birdR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- vol2birdR is an R package for calculating vertical profiles and other biological scatterers from weather radar data. The original **vol2bird** is written as a C-package and has been migrated to also work as an R package. ## Introduction The vol2birdR package provides necessary functions to process polar volume data of C-band and S-band radars into vertical profiles of biological scatterers. This package also enables libtorch and the MistNet model for segmentation of meteorological and biological signals. ## Calculating vertical profiles First, define a configuration instance, and modify configuration settings according to needs. ``` # load the library library(vol2birdR) # create a configuration instance config<-vol2bird_config() # modify the configuration instance as needed # in this example we set the maximum range to 25 km: config$rangeMax <- 25000 ``` The configuration object can be modified heavily. Learn more about the available options in the documentation of `vol2bird_config()` Note that configuration objects are copied by reference by default, and true copies that can be used independently should be assigned using: ``` config <- vol2bird_config() config_copy <- vol2bird_config(config) ``` Finally, the vertical profile can be calculated using function `vol2bird()`: ``` vol2bird(file="/your/input/pvolfile",config=config, vpfile="/your/output/vpfile") ``` The input pvolfile needs to be in ODIM HDF5 format, IRIS RAW format, or NEXRAD format. The output vpfile containing the profile will be in ODIM HDF5 format. ## MistNet ### Installation MistNet is a deep convolution neural net for segmenting out rain in S-band radar data, see the publication at https://besjournals.onlinelibrary.wiley.com/doi/full/10.1111/2041-210X.13280. To use MistNet, follow the following additional installation steps: After installing and loading vol2birdR, run `install_mistnet()` from R. This will download libtorch from the download section of https://pytorch.org as well as a wrapper library from AWS that enables the mistnet functionality: ``` # STEP 1: install mistnet libraries library(vol2birdR) install_mistnet() ``` After completing this step, the following command should evaluate to `TRUE`: ``` mistnet_exists() ``` Next, the pytorch mistnet model needs to be downloaded, which is hosted at http://mistnet.s3.amazonaws.com/mistnet_nexrad.pt. Note that this file is large, over 500Mb. It can be downloaded directly from R using `install_mistnet_model()`: ``` # STEP 2: download mistnet model: # install mistnet model into vol2birdR package: install_mistnet_model() ``` `install_mistnet_model()` installs the model by default into the vol2birdR package directory. As a result, when reinstalling vol2birdR the model file will have to be re-downloaded as well. Alternatively, you can store the model in an alternative location outside the vol2birdR package directory. This has the advantage that you don't have to re-download the model when reinstalling vol2birdR. Simply store the path of the mistnet_nexrad.pt file in the `mistNetPath` element of your configuration object (see `vol2bird_config()`) vol2birdR will automatically locate the file if it is located at `/opt/vol2bird/etc/mistnet_nexrad.pt`, which can be done as follows: ``` # create the directory # (in case of a permission-denied error, create the directory manually) dir.create("/opt/vol2bird/etc", recursive=TRUE) # download the model install_mistnet_model(path="/opt/vol2bird/etc/mistnet_nexrad.pt") ``` ### Using MistNet After installing the MistNet libraries and model file, a profile can be calculated as follows: ``` # define configuration object: config <- vol2bird_config() # enable MistNet: config$useMistNet <- TRUE # calculate the profile: vol2bird(file="/your/input/pvolfile", config=config, vpfile="/your/output/vpfile") ```
/scratch/gouwar.j/cran-all/cranData/vol2birdR/vignettes/vol2birdR.Rmd
#'Calculates per share Profit and Loss (PnL) at expiration for Straddle Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'According to Kakushadze and Serur (2018), non directional strategies can be divided into two subgroups: (a) volatility strategies that profit if the stock has large price movements (high volatility environment); and (b) sideways strategies that profit if the stock price remains stable (low volatility environment). Here, in this package only high volatility option strategies are discussed and represented through their graphs.\cr #'This is a volatility strategy consisting of a long position in an ATM (at the money) call option, and a long position in an ATM (at the money) put option with a strike price X. This is a net debit trade. The trader or investor has a neutral outlook. This is a capital gain strategy (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Straddle Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X Strike Price or eXercise price. #'@param C Call Premium or Call Price paid for the bought Call. #'@param P Put Premium or Put Price paid for the bought put. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'aStraddlePnL(25,25,2.40,1.70) #'aStraddlePnL(40,40,3,2,hl=0.7,hu=1.2) #'aStraddlePnL(1000,1010,18,10,hl=0.955,hu=1.055) #'@export aStraddlePnL <- function (ST,X,C,P,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Dr=C+P myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (pmax((myData$spot-X),0)+(pmax((X-myData$spot),0))-V0Dr) myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Straddle Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/01_aStraddlePnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Strangle Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'This is a volatility strategy consisting of a long position in an OTM (out of the money) call option with a strike price K1, and a long position in an OTM (out of the money) put option with a strike price K2. This is a net debit trade. However, because both call and put options are OTM (out of the money), this strategy is less costly to establish than a long straddle position. The flip side is that the movement in the stock price required to reach one of the break-even points is also more significant. The outlook of trader or investor is neutral. This is a capital gain strategy (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Strangle Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X1LP Lower Strike Price or eXercise price bought Put. #'@param X2HC Higher Strike Price or eXercise price bought Call. #'@param C Call Premium or Call Price paid for the bought Call. #'@param P Put Premium or Put Price paid for the bought put. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'aStranglePnL(25,22.50,27.50,0.85,1.40) #'aStranglePnL(46,44,52,2,4,hl=0.6,hu=1.6) #'aStranglePnL(1020,1015,1025,10,18,hl=0.95,hu=1.045) #'@export aStranglePnL <- function (ST,X1LP,X2HC,C,P,hl=0,hu=2.2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Dr=C+P myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (pmax((myData$spot-X2HC),0)+(pmax((X1LP-myData$spot),0))-V0Dr) myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble (myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = ' A Long Strangle ', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/02_aStranglePnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Guts Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'This is a volatility strategy consisting of a long position in an ITM (in the money call : ST is greater than call strike price of X1LC ) call option with a strike price X1LC, and a long position in an ITM (in the money put : ST is less than put strike of X2HP) put option with a strike price X2HP. This is a net debit trade. Since both call and put options are ITM, this strategy is more costly to establish than a long straddle position. The trader or investor has neutral outlook. This is a capital gain strategy (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Guts Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X2HP Higher Strike Price or eXercise price bought Put. #'@param X1LC Lower Strike Price or eXercise price bought Call. #'@param C Call Premium or Call Price paid for the bought Call. #'@param P Put Premium or Put Price paid for the bought put. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'gutsPnL(25,27,24.75,2.5,3) #'gutsPnL(46,48,44,2,4,hl=0.6,hu=1.6) #'gutsPnL(1020,1025,1015,10,18,hl=0.95,hu=1.045) #'@export gutsPnL <- function (ST,X2HP,X1LC,P,C,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Dr=C+P myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (pmax((myData$spot-X1LC),0)+(pmax((X2HP-myData$spot),0))-V0Dr) myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble (myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = ' Long Guts ', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/03_GutsPnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Long Call Synthetic Straddle Option Strategy and draws its Bar Plot displaying PnL in the plots tab. #'@description #'This volatility strategy (which is the same as a long straddle with the put replaced by a synthetic put) amounts to shorting stock and buying two ATM (or the nearest ITM call options with a strike price X. The trader’s outlook is neutral. This is a capital gain strategy (assuming S0 is greater than or equal to X and V0 is greater than (S0 minus X)) (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Long Call Synthetic Straddle Option Strategy and draw its graph in the plots tab. #'@param ST Spot Price at time T. #'@param X Strike Price or eXercise price. #'@param C1 Call Premium or Call Price paid for the first bought Call. #'@param C2 Call Premium or Call Price paid for the second bought Call. #'@param S0 Stock Price at which the stock is shorted. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'longCallSyntheticStraddlePnL(25,25,2,2,25.10) #'longCallSyntheticStraddlePnL(40,40,7,7,41,hl=0.4,hu=1.7) #'@export longCallSyntheticStraddlePnL <- function (ST,X,C1,C2,S0,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Cr=(S0- C1-C2) myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (V0Cr-myData$spot)+ (2* (pmax((myData$spot-X),0))) myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Long Call Synthetic Straddle Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/04_longCallSyntheticStraddlePnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Long Put Synthetic Straddle Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #' This volatility strategy (which is the same as a long straddle with the call replaced by a synthetic call) amounts to buying stock and buying two ATM (or the nearest ITM) put options with a strike price X. The outlook of investor or trader is neutral. This is capital gain strategy. This is a capital gain strategy (assuming S0 is less than or equal to X and V0 is greater than (X minus S0)) (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Long Put Synthetic Straddle Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X Strike Price or eXercise price. #'@param P1 Put Premium or Put Price paid for the first bought Put. #'@param P2 Put Premium or Put Price paid for the second bought Put. #'@param S0 Stock Price at which the stock is bought. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'longPutSyntheticStraddlePnL(25,25,2,2,25.10) #'longPutSyntheticStraddlePnL(40,40,5,5.2,40.2,hl=0.3,hu=1.7) #'@export longPutSyntheticStraddlePnL <- function (ST,X,P1,P2,S0,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Dr=(S0+P1+P2) myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (myData$spot-V0Dr)+ (2* (pmax((X-myData$spot),0))) myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Long Put Synthetic Straddle Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/05_longPutSyntheticStraddlePnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Strap Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'This is a volatility strategy consisting of a long position in two ATM (at the money) calls , and a long position in an ATM (at the money) put option with a strike price X. This is a net debit trade. The trader or investor has bullish outlook (Kakushadze & Serur, 2018) . #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Strap Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X Strike Price or eXercise price. #'@param C1 Call Premium or Call Price paid for first bought Call. #'@param C2 Call Premium or Call Price paid for bought Call. #'@param P Put Premium paid for the bought put. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'strapPnL(25,25,2.40,2.40,1.70) #'strapPnL(40,40,3,3,2,hl=0.7,hu=1.2) #'strapPnL(1000,1010,18,18,10,hl=0.955,hu=1.055) #'@export strapPnL <- function (ST,X,C1,C2,P,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Dr=C1+C2+P myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (2*pmax((myData$spot-X),0)+(pmax((X-myData$spot),0))-V0Dr) myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Strap Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Bullish Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/06_strapPnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Strip Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'This Strategy consists of a long call position (in an at the money call option) and a long position in two put options (at the money) with a strike price X. The Strip is a simple adjustment to the Straddle to make it more biased toward the downside. In buying a second put, the strategy retains its preference for high volatility but now with a more bearish slant (Cohen, 2016). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Strip Option Strategy and draw its graph in the Plots tab. EXAMPLE, Buy HypoVola December 9 call at $1.40 (outflow) and Buy two HypoVola December 9 Puts at $0.80 (outflow). This is a net debit trade and involves three cash outflows. The Bar Plot gets displayed in Plots tab. #'@param ST Spot Price at time T. #'@param X Strike Price or eXercise price. #'@param C Call Premium or Call Price paid for bought Call. #'@param PnL Profit and Loss #'@param P1 Put Premium paid for the first bought put. #'@param P2 Put Premium paid for the second bought put. #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'stripPnL(9,9,1.4,0.80,0.80) #'stripPnL(40,40,2.00,1.25,1.25,hl=0.85,hu=1.25) #'stripPnL(1000,1000,8,5.50,6.50,hl=0.985,hu=1.035) #'@export stripPnL <- function (ST,X,C,P1,P2,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Dr=C+P1+P2 myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (pmax((myData$spot-X),0)+2*pmax((X-myData$spot),0)-V0Dr) myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Strip Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Bearish Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/07_stripPnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Short Call Butterfly Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'This is a volatility strategy consisting of a short position in an ITM (in the money) call option with a strike price X1L, a long position in two ATM ( at the money) call options with a strike price X, and a short position in an OTM (out of the money) call option with a strike price X3H. The strikes are equidistant: X3H minus X equals to X minus X1L . This is a net credit trade. In this sense, this is an income strategy. The trader or investor has neutral outlook (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Short Call Butterfly Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X1L Lower Strike Price or eXercise price for one ITM shorted Call. #'@param X Strike Price or eXercise price for two ATM bought Calls. #'@param X3H Higher Strike Price or eXercise price for one OTM shorted Call. #'@param C1L Call Premium or Call Price received for the first ITM shorted Call. #'@param C Call Premium or Call Price paid for the two ATM bought Calls. #'@param C3H Call Premium or Call Price received for the one OTM shorted Call. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'shortCallButterflyPnL(50,50,45,55,5,9,3) #'shortCallButterflyPnL(400,400,375,425,6,9.5,7.5,hl=0.8,hu=1.2) #'@export shortCallButterflyPnL <- function (ST,X,X1L,X3H,C,C1L,C3H,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Cr= C1L+ C3H - (2*C) myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (2* (pmax((myData$spot-X),0))) - (pmax((myData$spot-X1L),0))- (pmax((myData$spot-X3H),0)) + V0Cr # myData$pl <- (V0Cr-myData$spot)+ (2* (pmax((myData$spot-X),0))) myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Short Call Butterfly Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/08_shortCallButterflyPnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Short Put Butterfly Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'This is a volatility strategy consisting of a short position in an ITM put option (in the money put; strike price greater than spot price) with a strike price X1H, a long position in two ATM (at the money) put options with a strike price X2, and a short position in an OTM put option (out of the money : strike price less than spot price) with a strike price X3L . The strikes are equidistant: X2 minus X3L equals to X1H minus X2. This is a net credit trade. In this sense, this is an income strategy However, the potential reward is sizably smaller than with a short straddle or a short strangle (albeit with a lower risk). The trader or investor has a neutral outlook (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Short Put Butterfly Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X1H Higher Strike Price or eXercise price for one ITM shorted Put. #'@param X2 Strike Price or eXercise price for two ATM bought Puts. #'@param X3L Higher Strike Price or eXercise price for one OTM shorted Put. #'@param P1H Put Premium or Put Price received for the first ITM shorted Put. #'@param P2 Put Premium or Put Price paid for the two ATM bought Puts. #'@param P3L Put Premium or Put Price received for the one OTM shorted Put. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'shortPutButterflyPnL(50,50,55,45,6,9,5) #'shortPutButterflyPnL(400,400,420,380,14,19,15,hl=0.9,hu=1.1) #'@export shortPutButterflyPnL <- function (ST,X2,X1H,X3L,P2,P1H,P3L,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Cr= P1H + P3L - (2*P2) myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (2* (pmax((X2-myData$spot),0))) - (pmax((X1H-myData$spot),0))- (pmax((X3L-myData$spot),0)) + V0Cr myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Short Put Butterfly Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/09_shortPutButterflyPnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Short Iron Butterfly Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'This volatility strategy is a combination of a bear put spread and a bull call spread and consists of a short position in an OTM put option (out of the money put : put Strike price is lower than spot price ) with a strike price X1L, a long position in an ATM (at the money) put option and an ATM (at the money) call option with a strike price X2M, and a short position in an OTM call option (out of the money call : call Strike price is higher than spot price ) with a strike price X3H. The strikes are equidistant: X2M minus X1L equals to X3H minus X2M . This is a net debit trade. The trader or investor has an outlook that is neutral (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Short Iron Butterfly Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X1L Lower Strike Price or eXercise price for one ITM shorted Put. #'@param X2M Medium trike Price or eXercise price for one bought Put and one bought Call. #'@param X3H Higher Strike Price or eXercise price for one OTM shorted Call. #'@param P1L Put Premium or Put Price received for the first ITM shorted Put. #'@param P2 Put Premium or Put Price paid for the bought Put. #'@param C2 Put Premium or Put Price paid for the bought Call. #'@param C3H Call Premium or Put Price received for the one OTM shorted Call. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'shortIronButterflyPnL(52,45,50,55,2,4,7,5) #'shortIronButterflyPnL(405,400,410,420,8,12,14.5,9,hl=0.9,hu=1.1) #'@export shortIronButterflyPnL <- function (ST,X1L,X2M,X3H,P1L,P2,C2,C3H,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Dr= P2+C2 -P1L -C3H myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (pmax((X2M-myData$spot),0)) + (pmax((myData$spot-X2M),0)) - (pmax((X1L-myData$spot),0))- (pmax((myData$spot-X3H),0)) - V0Dr myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Short Iron Butterfly Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/10_shortIronButterflyPnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Short Call Condor Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'This is a volatility strategy consisting of a short position in an ITM call option with a strike price X1L, a long position in an ITM call option with a higher strike price X2Ml, a long position in an OTM call option with a strike price X3Mu, and a short position in an OTM call option with a higher strike price X4H. All strikes are equidistant: X4H minus X3Mu equals to X3Mu minus X2Ml; equals to X2Mu minus X1L. This is a relatively low net credit trade. The trader or investor has a neutral outlook (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Short Call Condor Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X1L Lower Strike Price or eXercise price for one ITM shorted Call. #'@param X2Ml Middle-low Strike Price or eXercise price for two middle strike bought Calls. #'@param X3Mu Middle-upper Strike Price or eXercise price for two middle strike bought Calls. #'@param X4H Higher Strike Price or eXercise price for one OTM shorted Call. #'@param C1L Call Premium or Call Price received for the one ITM shorted Call. #'@param C2Ml Call Premium or Call Price paid for the middle-low bought Call. #'@param C3Mu Call Premium or Call Price paid for the middle-upper bought Call. #'@param C4H Call Premium or Call Price received for the one OTM shorted Call. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'shortCallCondorPnL(52,45,50,55,60,10,7,4,3.) #'shortCallCondorPnL(415,400,420,440,460,50,35,22,16,hl=0.95,hu=1.125) #'@export shortCallCondorPnL <- function (ST,X1L,X2Ml,X3Mu,X4H,C1L,C2Ml,C3Mu,C4H,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Cr= C1L+ C4H - C2Ml -C3Mu myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (pmax((myData$spot-X2Ml),0))+ (pmax((myData$spot-X3Mu),0)) - (pmax((myData$spot-X1L),0))- (pmax((myData$spot-X4H),0)) + V0Cr myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Short Call Condor Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/11_shortCallCondorPnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Short Put Condor Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'This is a volatility strategy consisting of a short position in an OTM Put option with a strike price X1L, a long position in an OTM Put option with a higher strike price X2Ml, a long position in an ITM Put option with a strike price X3Mu, and a short position in an ITM Put option with a higher strike price X4H. All strikes are equidistant: X4H minus X3Mu equals to X3Mu minus X2Ml; equals to X2Mu minus X1L. This is a relatively low net credit trade. As with a short put butterfly, the potential reward is sizably smaller than with a short straddle or a short strangle (albeit with a lower risk). So, this is a capital gain (rather than an income) strategy. The trader or investor has neutral outlook (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Short Put Condor Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X1L Lower Strike Price or eXercise price for one ITM shorted Put. #'@param X2Ml Middle-low Strike Price or eXercise price for middle strike bought Put. #'@param X3Mu Middle-upper Strike Price or eXercise price for middle strike bought Put. #'@param X4H Higher Strike Price or eXercise price for one OTM shorted Put. #'@param P1L Put Premium or Put Price received for the one OTM shorted Put. #'@param P2Ml Put Premium or Put Price paid for the middle-low bought Put. #'@param P3Mu Put Premium or Put Price paid for the middle-upper bought Put. #'@param P4H Put Premium or Put Price received for the one ITM shorted Put. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'shortPutCondorPnL(52,45,50,55,60,2,3,7,10.) #'shortPutCondorPnL(425,400,420,440,460,16,22,35,50,hl=0.9,hu=1.125) #'@export shortPutCondorPnL <- function (ST,X1L,X2Ml,X3Mu,X4H,P1L,P2Ml,P3Mu,P4H,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Cr= P1L+ P4H - P2Ml -P3Mu myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (pmax((X2Ml-myData$spot),0))+(pmax((X3Mu-myData$spot),0))- (pmax((X1L-myData$spot),0))- (pmax((X4H-myData$spot),0)) + V0Cr myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Short Put Condor Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/12_shortPutCondorPnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Short Iron Condor Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'This volatility strategy is a combination of a bear put spread and a bull call spread and consists of a short position in an OTM put option (out of the money put : put Strike price is lower than spot price X1L ) with a strike price X1L, a long position in put option with higher Strike X2 price and a long position OTM (out of the money) call option with a strike price X3, and a short position in call option with a higher strike price X4H. The strikes are equidistant: X2 minus X1L equals to X4H minus X3 . This is a net debit trade. The trader or investor has an outlook that is neutral (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Short Iron Condor Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X1L Lower Strike Price or eXercise price for one OTM shorted Put. #'@param X2 Strike Price or eXercise price for one bought Put. #'@param X3 Strike Price or eXercise price for one bought Call. #'@param X4H Higher Strike Price or eXercise price for one OTM shorted Call. #'@param P1L Put Premium or Put Price received for the first OTM shorted Put. #'@param P2 Put Premium or Put Price paid for the bought Put. #'@param C3 Put Premium or Put Price paid for the bought Call. #'@param C4H Call Premium or Put Price received for the one OTM shorted Call. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'shortIronCondorPnL(52,45,50,55,60,2,4,5,3) #'shortIronCondorPnL(405,400,410,420,430,8,11,13,9,hl=0.95,hu=1.1) #'@export shortIronCondorPnL <- function (ST,X1L,X2,X3,X4H,P1L,P2,C3,C4H,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Dr= P2+C3 -P1L -C4H myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (pmax((X2-myData$spot),0)) + (pmax((myData$spot-X3),0)) - (pmax((X1L-myData$spot),0))- (pmax((myData$spot-X4H),0)) - V0Dr myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.6,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Short Iron Condor Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility / Neutral Outlook', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/13_shortIronCondorPnL.R
#'Calculates per share Profit and Loss (PnL) at expiration for Long Box Option Strategy and draws its Bar Plot displaying PnL in the Plots tab. #'@description #'The Long Box is a complex strategy that can (in some jurisdictions) have beneficial effects for tax planning from year to year. If your incentive for this strategy is a tax play, you should consult with your tax advisor beforehand to evaluate whether or not it is valid where you live and trade to invest (Cohen, 2015).\cr #'This volatility strategy can be viewed as a combination of a bull call spread and a bear put spread, and consists of a long position in an ITM put option with a strike price X1H, a short position in an OTM put option with a lower strike price X2, a long position in an ITM call option with the strike price X2, and a short position in an OTM call option with the strike price X1H. The trader or investor has an outlook that is neutral (Kakushadze & Serur, 2018). #'@details #'According to conceptual details given by Cohen (2015), and a closed form solution provided by Kakushadze and Serur (2018), this method is developed, and the given examples are created, to compute per share Profit and Loss at expiration for Long Box Option Strategy and draw its graph in the Plots tab. #'@param ST Spot Price at time T. #'@param X1H Higher Strike Price or eXercise price for one ITM long Put and one OTM shorted call . #'@param X2 Strike Price or eXercise price for one shorted Put and one long call. #'@param P1 Put Premium or Put Price received for the shorted Put. #'@param C2 Put Premium or Put Price paid for the bought Call. #'@param P3 Put Premium or Put Price paid for the bought Put. #'@param C4 Call Premium or Put Price received for the shorted Call. #'@param PnL Profit and Loss #'@param spot Spot Price #'@param pl Profit and Loss #'@param myData Data frame #'@param myTibble tibble #'@param hl lower bound value for setting lower-limit of x-axis displaying spot price. #'@param hu upper bound value for setting upper-limit of x-axis displaying spot price. #'@return graph of the strategy #'@importFrom magrittr %>% #'@importFrom ggplot2 ggplot #'@importFrom ggplot2 geom_point #'@importFrom ggplot2 scale_fill_manual #'@importFrom ggplot2 scale_color_manual #'@importFrom ggplot2 geom_col #'@importFrom tibble as_tibble #'@importFrom dplyr mutate #'@importFrom ggplot2 aes #'@importFrom ggplot2 element_line #'@importFrom ggplot2 element_rect #'@importFrom ggplot2 element_text #'@importFrom ggplot2 geom_line #'@importFrom ggplot2 geom_text #'@importFrom ggplot2 labs #'@importFrom ggplot2 scale_colour_manual #'@importFrom ggplot2 scale_y_continuous #'@importFrom ggplot2 theme #'@examples #'longBoxPnL(34,40,30,1,6,7,2) #'@export longBoxPnL <- function (ST,X1H,X2,P1,C2,P3,C4,hl=0,hu=2,spot=spot,pl=pl,myData=myData,myTibble=myTibble,PnL=PnL){ V0Dr= C2+P3 -P1 -C4 myData <- data.frame (spot = c((ST*hl):(ST*hu))) myData$pl <- (pmax((X1H-myData$spot),0))- (pmax((X2-myData$spot),0))+ (pmax((myData$spot-X2),0))- (pmax((myData$spot- X1H),0)) -V0Dr myData$pl = round(myData$pl, digits=2) myData$spot = round(myData$spot, digits=2) myTibble <- as_tibble(myData) myTbColored <- myTibble %>% mutate(PnL = pl >= 0) ggplot(myTbColored,aes(x=spot,y=pl,fill=PnL,label=pl)) + geom_col(position = "identity") + scale_fill_manual(values = c("#D47188","#1B7979"), guide= "none" ) + geom_point(aes(color=PnL))+ scale_color_manual(values = c("red","chartreuse"), guide= "none" ) + geom_text(nudge_y = 0.000,size= 3, color="navyblue")+ theme(plot.caption = element_text(colour = 'lightsteelblue3'))+ theme(axis.line = element_line(linetype = 'solid',colour ="darkmagenta" ))+ theme(axis.ticks = element_line(size = 1,colour = "deeppink1"))+ theme(panel.grid.major = element_line(colour = 'lightsteelblue1'))+ theme(panel.grid.minor = element_line(colour = 'thistle2'))+ theme(axis.title = element_text(colour = 'blue'))+ theme(plot.title = element_text(colour = 'brown3', vjust = 1))+ theme(panel.background = element_rect(fill = '#F2F2F9'))+ theme(plot.background = element_rect(fill = '#E6E6FA', colour = 'aquamarine4', linetype = 'dashed'))+ labs(title = 'Long Box Strategy', x = 'Spot Price ($) at Expiration', y = 'PnL ($) at Expiration', subtitle = 'High Volatility/ Tax Planning Purpose (in some jurisdictions only)', caption = 'volatilityTrader / MaheshP Kumar') }
/scratch/gouwar.j/cran-all/cranData/volatilityTrader/R/14_longBoxPnL.R
#' Add mode bar button to rotate the plot #' #' @param p The \code{\link{volcano3D}} plot #' @param rotate_icon_path The svg icon path for rotation. If `NULL` a play #' button is used #' @param stop_icon_path The svg icon path for stop button. If `NULL` a pause #' button is used #' @param rotate_colour The colour for the rotate button (default="#c7c7c7") #' @param stop_colour The colour for the stop button (default='#ff6347', #' a.k.a 'tomato') #' @param scale Scaling for rotation button #' @param speed The rotation speed #' @param shiny_event_names If using shiny, pass in any shiny event names which #' should stop rotation when triggered (e.g. shiny_event_names = c('replot')) #' @importFrom htmlwidgets JS onRender #' @importFrom plotly config #' @return Returns a rotating cylindrical 3D plotly plot featuring variables on #' a tri-axis radial graph with the -log10(multi-group test p-value) on the #' z-axis #' @seealso \code{\link{volcano3D}} #' @references #' Lewis, Myles J., et al. (2019). #' \href{https://pubmed.ncbi.nlm.nih.gov/31461658/}{ #' Molecular portraits of early rheumatoid arthritis identify clinical and #' treatment response phenotypes.} #' \emph{Cell reports}, \strong{28}:9 #' @importFrom plotly plot_ly add_trace add_text layout #' @importFrom magrittr %>% #' @importFrom grDevices hsv rgb #' @keywords hplot iplot #' @concept volcanoplot #' @export #' @examples #' data(example_data) #' syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, #' data = t(syn_example_rld)) #' #' p <- volcano3D(syn_polar, #' label_rows = c("COBL", "TREX2")) #' add_animation(p) #' #' @export add_animation <- function(p, rotate_icon_path=NULL, stop_icon_path=NULL, rotate_colour="#c7c7c7", stop_colour='#ff6347', scale='scale(0.4) translate(-4, -4)', speed = 320, shiny_event_names=c()) { . <- NULL # to appease the CRAN note if(!inherits(p, "plotly")) stop("Not a plotly plot") if(is.null(rotate_icon_path)){ rotate_icon_path <- paste0("M20 33l12-9-12-9v18zm4-29C12.95 4 4 12.95 4", " 24s8.95 20 20 20 20-8.95 20-20S35.05 4 24 ", "4zm0 36c-8.82 0-16-7.18-16-16S15.18 8 24", " 8s16 7.18 16 16-7.18 16-16 16z") } if(is.null(stop_icon_path)){ stop_icon_path <- paste0("M24 4C12.95 4 4 12.95 4 24s8.95 20 20 20 ", "20-8.95 20-20S35.05 4 24 4zm-2 28h-4V16h4v16zm8", " 0h-4V16h4v16z") } button_script <- readLines(system.file("/spin_function/spin_button.js", package = "volcano3D")) %>% gsub("rotate_icon_path", rotate_icon_path, .) %>% gsub("stop_icon_path", stop_icon_path, .) %>% gsub("rotate_colour", rotate_colour, .) %>% gsub("stop_colour", stop_colour, .) rotate_button <- list( name = "rotate", title = 'Rotate', icon= list( path = rotate_icon_path, transform = scale ), val=FALSE, attr='rotating', click = htmlwidgets::JS(button_script)) js_rotation <- readLines(system.file("spin_function/rotation.js", package = "volcano3D")) %>% gsub('rotation_speed', speed, .) %>% gsub("rotate_colour", rotate_colour, .) if(length(shiny_event_names) > 0){ print("catching") event_name_str <- paste0("'", paste(shiny_event_names, collapse="', '"), "'") print(event_name_str) js_rotation <- gsub("shiny_event_names", event_name_str, js_rotation) } p %>% config(modeBarButtonsToAdd = list(rotate_button)) %>% htmlwidgets::onRender(js_rotation) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/add_animation.R
#' Boxplot to compare groups #' #' Plots the expression of a specific row in expression to compare the three #' groups in a boxplot using either ggplot or plotly. #' @param polar A 'volc3d' object including expression data from groups of #' interest. Created by \code{\link{polar_coords}}. #' @param value The column name or number in \code{polar@data} to be #' analysed #' @param box_colours The fill colours for each box assigned in order of #' levels_order. Default = c('green3', 'blue', 'red') ). #' @param test The statistical test used to compare expression. #' Allowed values include: \itemize{ #' \item \code{polar_pvalue} (default) and 'polar_padj' for the pvalues #' and adjusted pvalues in the polar object. #' \item \code{polar_multi_pvalue} and \code{polar_multi_padj} for the pvalues #' and adjusted pvalues across all groups using the #' \code{polar@multi_group_test } columns. #' \item \code{\link[stats]{t.test}} (parametric) and #' \code{\link[stats]{wilcox.test}} (non-parametric). Perform comparison #' between groups of samples. #' \item \code{\link[stats]{anova}} (parametric) and #' \code{\link[stats]{kruskal.test}} (non-parametric). Perform one-way ANOVA #' test comparing multiple groups. } #' @param levels_order A character vector stating the contrast groups to be #' plotted, in order. If `NULL` this defaults to the levels in #' `polar@outcome`. #' @param my_comparisons A list of contrasts to pass to #' \code{\link[ggpubr]{stat_compare_means}}. If `NULL` (default) all contrast #' pvalues are calculated and plotted. #' @param text_size The font size of text (default = 10) #' @param stat_colour Colour to print statistics (default="black"). #' @param stat_size The font size of statistical parameter (default = 3). #' @param step_increase The distance between statistics on the y-axis #' (default = 0.05). #' @param plot_method Whether to use 'plotly' or 'ggplot'. Default is 'ggplot' #' @param ... Other parameters for \code{\link[ggpubr]{stat_compare_means}} #' @return Returns a boxplot featuring the differential expression #' between groups in comparison with annotated pvalues. #' @importFrom ggpubr compare_means ggboxplot stat_pvalue_manual #' stat_compare_means #' @importFrom plotly layout plot_ly add_trace add_markers #' @importFrom utils combn #' @importFrom grDevices hsv col2rgb #' @importFrom ggplot2 theme ggplot labs geom_path geom_path geom_text annotate #' geom_point scale_color_manual aes geom_jitter element_rect aes_string #' element_text #' @importFrom methods is #' @importFrom stats setNames #' @keywords hplot #' @references #' Lewis, Myles J., et al. (2019). #' \href{https://pubmed.ncbi.nlm.nih.gov/31461658/}{ #' Molecular portraits of early rheumatoid arthritis identify clinical and #' treatment response phenotypes.} #' \emph{Cell reports}, \strong{28}:9 #' @export #' @examples #' data(example_data) #' syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, #' data = t(syn_example_rld)) #' #' boxplot_trio(syn_polar, value = "COBL", plot_method="plotly") #' boxplot_trio(syn_polar, value = "COBL") boxplot_trio <- function(polar, value, box_colours = c('green3', 'blue', 'red'), test = "polar_pvalue", levels_order = NULL, my_comparisons = NULL, text_size = 10, stat_colour = "black", stat_size = 3, step_increase = 0.05, plot_method="ggplot", ...){ # Check the input data if (is(polar, "polar")) { args <- as.list(match.call())[-1] return(do.call(boxplot_trio_v1, args)) # for back compatibility } if(! is(polar, "volc3d")) stop("Not a 'volc3d' class object") outcome <- polar@outcome expression <- t(polar@data) pvalues <- polar@pvals padj <- polar@padj if(! test %in% c("polar_pvalue", "polar_padj", "polar_multi_pvalue", "polar_multi_padj", "t.test", "wilcox.test", "anova", "kruskal.test")) { stop(paste("expression must be a data frame or c('polar_pvalues',", "'polar_padj', 'polar_multi_pvalue', 'polar_multi_padj',", "'t.test', 'wilcox.test', 'anova', 'kruskal.test')")) } if(is.null(levels_order)) { levels_order <- levels(outcome) } if(! all(levels_order %in% levels(outcome))){ stop(paste('levels_order must be a character vector defining the order', "of levels in 'outcome'")) } if(length(box_colours) != length(levels_order)){ stop(paste0('The length of box_colours must match teh length of', 'levels_order')) } # Convert to hex colours for plotly box_colours <- unlist(lapply(box_colours, function(x) { if(! grepl("#", x) & class(try(col2rgb(x), silent = TRUE))[1] == "try-error") { stop(paste(x, 'is not a valid colour')) } else if (! grepl("#", x) ) { y <- col2rgb(x)[, 1] x <- rgb(y[1], y[2], y[3], maxColorValue=255) } return(x) })) if(length(value) > 1) stop("value must be of length 1") if(! value %in% rownames(expression)) { stop("value/gene is not in rownames(expression)") } if(! plot_method %in% c('plotly', 'ggplot')){ stop("plot_method must be either plotly or ggplot") } colour_map <- setNames(box_colours, levels_order) if(is.character(value)) { index <- which(rownames(expression) == value) } if(is.null(my_comparisons)) { comps <- levels_order my_comparisons <- lapply(seq_len(ncol(combn(comps, 2))), function(i) { as.character(combn(comps, 2)[, i]) }) } df <- data.frame("group" = outcome, "row" = expression[value, ]) df <- df[! is.na(df$row), ] df <- df[df$group %in% levels_order, ] # re-level based on defined order df$group <- factor(df$group, levels_order) df$col <- factor(df$group, labels=colour_map[match(levels(df$group), names(colour_map))]) map_pos <- setNames(seq_along(levels(df$group)), levels(df$group)) # Calculate the p-values depending on test if(test %in% c("t.test", "wilcox.test", "anova", "kruskal.test")){ pvals <- compare_means(formula = row ~ group, data = df, comparisons = my_comparisons, method = test, step.increase = step_increase, size=stat_size) if (test %in% c("t.test", "wilcox.test")) { pvals$x.position <- map_pos[pvals$group1] + (map_pos[pvals$group2] - map_pos[pvals$group1])/2 pvals$y.position <- max(df$row, na.rm=TRUE)* (1.01 + step_increase*c(seq_len(nrow(pvals))-1)) pvals$new_p_label <- pvals$p.format } else pvals <- pvals$p # group comparisons } else if (! grepl("multi", test)){ pvals <- switch(test, "polar_pvalue" = pvalues[value, 2:4], "polar_padj" = padj[value, 2:4]) pvals <- data.frame(p = pvals) pvals$group1 <- levels(outcome)[c(1,1,2)] pvals$group2 <- levels(outcome)[c(2,3,3)] pvals$p.format <- format(pvals$p, digits=2) pvals$method <- test pvals$y.position <- max(df$row, na.rm=TRUE) pvals$comp <- paste0(pvals$group1, "_", pvals$group2) pvals$x.position <- map_pos[pvals$group1] + (map_pos[pvals$group2] - map_pos[pvals$group1])/2 pvals$y.position <- pvals$y.position[1]* (1.01 + step_increase*(seq_len(nrow(pvals))-1)) comp_use <- unlist(lapply(my_comparisons, function(x) { c(paste0(x[1], "_", x[2]), paste0(x[2], "_", x[1])) })) pvals <- pvals[pvals$comp %in% comp_use, ] # multi group comparisons } else{ # polar_multi_test pvals <- switch(test, "polar_multi_pvalue" = pvalues[value, 1], "polar_multi_padj" = padj[value, 1]) } if(plot_method == 'ggplot'){ p <- ggboxplot(data = df, x = "group", y = "row", xlab = "", ylab = rownames(polar@pvals)[index], fill = "group", color = "group", palette = box_colours, outlier.shape = NA, alpha = 0.3) + geom_jitter(data=df, height = 0, width = 0.30, aes_string(color="group")) + theme(legend.position = "none", text = element_text(size = text_size), plot.background = element_rect(fill="transparent", color=NA), panel.background = element_rect(fill="transparent", colour=NA), legend.background = element_rect(fill="transparent", colour=NA)) if(! grepl("multi", test) & !(test %in% c("anova", "kruskal.test"))){ p <- p + stat_pvalue_manual( data = pvals, label = "p.format", xmin = "group1", xmax = "group2", step.increase = step_increase, y.position = "y.position", color = stat_colour, size=stat_size, ...) } else{ # multi group comparison p <- p + annotate("text", x = 0.5 + length(unique(df$group))/2, y = Inf, vjust = 2, hjust = 0.5, color = stat_colour, label = paste("p =", format(pvals, digits = 2))) } } else{ p <- df %>% plot_ly() %>% add_trace(x = ~as.numeric(group), y = ~row, type = "box", colors = levels(df$col), color = ~col, opacity=0.5, marker = list(opacity = 0), hoverinfo="none", showlegend = FALSE) %>% add_markers(x = ~jitter(as.numeric(group)), y = ~row, marker = list(size = 6, color=~col), hoverinfo = "text", text = paste0(rownames(df), "<br>Group: ", df$group, "<br>Expression: ", format(df$row, digits = 3)), showlegend = FALSE) %>% layout(legend = list(orientation = "h", x =0.5, xanchor = "center", y = 1, yanchor = "bottom" ), xaxis = list(title = "", tickvals = 1:3, ticktext = levels(df$group)), yaxis = list(title = value)) lines <- list() if(! grepl("multi", test)){ for (i in seq_len(nrow(pvals))) { line <- list(line=list(color = stat_colour)) line[["x0"]] <- map_pos[pvals$group1][i] line[["x1"]] <- map_pos[pvals$group2][i] line[c("y0", "y1")] <- pvals$y.position[i] lines <- c(lines, list(line)) } a <- list( x = as.numeric(pvals$x.position), y = pvals$y.position, text = format(pvals$p.format, digits=3), xref = "x", yref = "y", yanchor = "bottom", font = list(color = stat_colour), showarrow = FALSE ) p <- p %>% layout(annotations = a, shapes=lines) } else{ a <- list( x = 2, y = step_increase + max(df$row, na.rm=TRUE), text = format(pvals, digits=3), xref = "x", yref = "y", font = list(color = stat_colour), showarrow = FALSE ) p <- p %>% layout(annotations = a) } } return(p) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/boxplot_trio.R
#' @importFrom grDevices col2rgb #' @importFrom stats setNames boxplot_trio_v1 <- function(polar, value, box_colours = c('green3', 'blue', 'red'), test = "polar_pvalue", levels_order = NULL, my_comparisons = NULL, text_size = 10, stat_colour = "black", stat_size = 3, step_increase = 0.05, plot_method="ggplot", ...){ sampledata <- polar@sampledata expression <- polar@expression pvalues <- polar@pvalues if(! test %in% c("polar_pvalue", "polar_padj", "polar_multi_pvalue", "polar_multi_padj", "t.test", "wilcox.test", "anova", "kruskal.test")) { stop(paste("expression must be a data frame or c('polar_pvalues',", "'polar_padj', 'polar_multi_pvalue', 'polar_multi_padj',", "'t.test', 'wilcox.test', 'anova', 'kruskal.test')")) } if(is.null(levels_order)) { levels_order <- levels(sampledata[, polar@contrast]) } if(! inherits(levels_order, "character")) { stop("levels_order must be a character vector") } if(! all(levels_order %in% levels(sampledata[, polar@contrast]))){ stop(paste('levels_order must be a character vector defining the order', 'of levels in sampledata[, contrast]')) } if(length(box_colours) != length(levels_order)){ stop(paste0('The length of box_colours must match teh length of', 'levels_order')) } # Convert to hex colours for plotly box_colours <- unlist(lapply(box_colours, function(x) { if(! grepl("#", x) & class(try(col2rgb(x), silent = TRUE))[1] == "try-error") { stop(paste(x, 'is not a valid colour')) } else if (! grepl("#", x) ) { y <- col2rgb(x)[, 1] x <- rgb(y[1], y[2], y[3], maxColorValue=255) } return(x) })) if(! is.data.frame(sampledata)) { stop("sampledata must be a data frame") } if(! inherits(expression, c("data.frame", "matrix"))) { stop("expression must be a data frame or matrix") } if(! inherits(value, c("character", "numeric"))) { stop("value must be a character") } if(length(value) > 1) stop("value must be of length 1") if(! value %in% rownames(expression)) { stop("value/gene is not in rownames(expression)") } if(! identical(colnames(expression), as.character(sampledata$ID))) { stop("expression and sampledata misalligned") } if(grepl("multi", test) & is.null(polar@multi_group_test)){ stop(paste("A multi-group test parameter is required in pvalues to use", test)) } if(! plot_method %in% c('plotly', 'ggplot')){ stop("plot_method must be either plotly or ggplot") } colour_map <- setNames(box_colours, levels_order) sampledata$comp <- sampledata[, polar@contrast] expression <- expression[, match(as.character(sampledata$ID), colnames(expression))] if(is.character(value)) { index <- which(rownames(expression) == value) } if(is.null(my_comparisons)) { comps <- levels_order my_comparisons <- lapply(seq_len(ncol(combn(comps, 2))), function(i) { as.character(combn(comps, 2)[, i]) }) } df <- data.frame("ID" = sampledata$ID, "group" = sampledata$comp, "row" = as.numeric(as.character(expression[value, ]))) df <- df[! is.na(df$row), ] df <- df[df$group %in% levels_order, ] # relevel based on defined order df$group <- factor(df$group, levels_order) df$col <- factor(df$group, labels=colour_map[match(levels(df$group), names(colour_map))]) map_pos <- setNames(seq_along(levels(df$group)), levels(df$group)) # Calculate the pvalues depending on test if(test %in% c("t.test", "wilcox.test", "anova", "kruskal.test")){ pvals <- compare_means(formula = row ~ group, data = df, comparisons = my_comparisons, method = test, step.increase = step_increase, size=stat_size) pvals$x.position <- map_pos[pvals$group1] + (map_pos[pvals$group2] - map_pos[pvals$group1])/2 pvals$y.position <- max(df$row, na.rm=TRUE)* (1.01 + step_increase*c(seq_len(nrow(pvals))-1)) pvals$new_p_label <- pvals$p.format # groups comparisons } else if (! grepl("multi", test)){ if(! any(grepl(gsub("polar_", "", test), colnames(pvalues)))){ stop(paste(test, "tests must have", gsub(".*_", "", test), "columns in polar@pvalues")) } pvals <- pvalues[value, ] pvals <- pvals[, grepl(gsub("polar_", "", test), colnames(pvals))] if(! is.null(polar@multi_group_test)){ pvals <- pvals[, ! grepl(polar@multi_group_test, colnames(pvals))] } colnames(pvals) <- gsub(paste0("_", gsub("polar_", "", test)), "", colnames(pvals)) rownames(pvals) <- "p" pvals <- data.frame(t(pvals)) pvals$group1 <- gsub("_.*", "", rownames(pvals)) pvals$group2 <- gsub(".*_", "", rownames(pvals)) pvals$p.format <- format(pvals$p, digits=2) pvals$method <- test pvals$y.position <- max(df$row, na.rm=TRUE) pvals$comp <- paste0(pvals$group1, "_", pvals$group2) pvals$x.position <- map_pos[pvals$group1] + (map_pos[pvals$group2] - map_pos[pvals$group1])/2 pvals$y.position <- pvals$y.position[1]* (1.01 + step_increase*(seq_len(nrow(pvals))-1)) comp_use <- unlist(lapply(my_comparisons, function(x) { c(paste0(x[1], "_", x[2]), paste0(x[2], "_", x[1])) })) pvals <- pvals[pvals$comp %in% comp_use, ] # muti group comparisons } else{ if(! any(grepl(gsub("polar_multi_", "", test), colnames(pvalues)))){ stop(paste(test, "tests must have", gsub(".*_", "", test), "columns in polar@pvalues")) } pvals <- pvalues[value, ] pvals <- pvals[, grepl(gsub("polar_multi_", "", test), colnames(pvals))] pvals <- pvals[, grepl(polar@multi_group_test, colnames(pvals))] } if(plot_method == 'ggplot'){ p <- ggboxplot(data = df, x = "group", y = "row", xlab = "", ylab = paste(polar@pvalues$label[index], "Expression"), fill = "group", color = "group", palette = box_colours, outlier.shape = NA, alpha = 0.3) + geom_jitter(data=df, height = 0, width = 0.30, aes_string(color="group")) + theme(legend.position = "none", text = element_text(size = text_size), plot.background = element_rect(fill="transparent", color=NA), panel.background = element_rect(fill="transparent", colour=NA), legend.background = element_rect(fill="transparent", colour=NA)) if(! grepl("multi", test)){ p <- p + stat_pvalue_manual( data = pvals, label = "p.format", xmin = "group1", xmax = "group2", step.increase = step_increase, y.position = "y.position", color = stat_colour, size=stat_size, ...) } else{ # muti group comparison p <- p + annotate("text", x = 0.5 + length(unique(df$group))/2, y = Inf, vjust = 2, hjust = 0.5, color = stat_colour, label = paste("p =", format(pvals, digits = 2))) } } else{ p <- df %>% plot_ly() %>% add_trace(x = ~as.numeric(group), y = ~row, type = "box", colors = levels(df$col), color = ~col, opacity=0.5, marker = list(opacity = 0), hoverinfo="none", showlegend = FALSE) %>% add_markers(x = ~jitter(as.numeric(group)), y = ~row, marker = list(size = 6, color=~col), hoverinfo = "text", text = ~paste0(ID, "<br>Group: ", group, "<br>Expression: ", row), showlegend = FALSE) %>% layout(legend = list(orientation = "h", x =0.5, xanchor = "center", y = 1, yanchor = "bottom" ), xaxis = list(title = polar@contrast, tickvals = 1:3, ticktext = levels(df$group)), yaxis = list(title = paste(value, "Expression"))) lines <- list() if(! grepl("multi", test)){ for (i in seq_len(nrow(pvals))) { line <- list(line=list(color = stat_colour)) line[["x0"]] <- map_pos[pvals$group1][i] line[["x1"]] <- map_pos[pvals$group2][i] line[c("y0", "y1")] <- pvals$y.position[i] lines <- c(lines, list(line)) } a <- list( x = as.numeric(pvals$x.position), y = pvals$y.position, text = format(pvals$p.format, digits=3), xref = "x", yref = "y", yanchor = "bottom", font = list(color = stat_colour), showarrow = FALSE ) p <- p %>% layout(annotations = a, shapes=lines) } else{ a <- list( x = 2, y = step_increase + max(df$row, na.rm=TRUE), text = format(pvals, digits=3), xref = "x", yref = "y", font = list(color = stat_colour), showarrow = FALSE ) p <- p %>% layout(annotations = a) } } return(p) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/boxplot_trio_old.R
#' 2 x 3 factor DESeq2 analysis #' #' Experimental function for performing 2x3 factor DESeq2 analyses. Output can #' be passed to [deseq_2x3_polar()] and subsequently plotted. Example usage #' would include comparing gene expression against a binary outcome e.g. #' response vs non-response, across 3 drugs: the design would be `~ response` #' and `group` would refer to the medication column in the metadata. #' #' @param object An object of class 'DESeqDataSet' containing full dataset #' @param design Design formula. The main contrast is taken from the last term #' of the formula and must be a binary factor. #' @param group Character value for the column with the 3-way grouping factor #' within the sample information data `colData` #' @param ... Optional arguments passed to `DESeq()`. #' @return Returns a list of 3 DESeq2 results objects which can be passed onto #' [deseq_2x3_polar()] #' @examples #' \donttest{ #' # Basic DESeq2 set up #' library(DESeq2) #' #' counts <- matrix(rnbinom(n=3000, mu=100, size=1/0.5), ncol=30) #' rownames(counts) <- paste0("gene", 1:100) #' cond <- rep(factor(rep(1:3, each=5), labels = c('A', 'B', 'C')), 2) #' resp <- factor(rep(1:2, each=15), labels = c('non.responder', 'responder')) #' metadata <- data.frame(drug = cond, response = resp) #' #' # Full dataset object construction #' dds <- DESeqDataSetFromMatrix(counts, metadata, ~response) #' #' # Perform 3x DESeq2 analyses comparing binary response for each drug #' res <- deseq_2x3(dds, ~response, "drug") #' #' # Generate polar object #' obj <- deseq_2x3_polar(res) #' #' # 2d plot #' radial_plotly(obj) #' #' # 3d plot #' volcano3D(obj) #' } #' #' @export deseq_2x3 <- function(object, design, group, ...) { # Check packages and input data if (!requireNamespace("DESeq2", quietly = TRUE)) { stop("Can't find package DESeq2. Try: BiocManager::install('DESeq2')", call. = FALSE) } if (!requireNamespace("SummarizedExperiment", quietly = TRUE)) { stop("Can't find package SummarizedExperiment. Try: BiocManager::install('SummarizedExperiment')", call. = FALSE) } if (!inherits(object, "DESeqDataSet")) stop("Not a DESeqDataSet object") counts <- SummarizedExperiment::assay(object) colDat <- SummarizedExperiment::colData(object) termsDE <- attr(terms(design), "term.labels") contrast <- termsDE[length(termsDE)] if (nlevels(colDat[, contrast]) != 2) { stop(contrast, " is not binary in `design`") } if (!group %in% colnames(colDat)) { stop(group, " is not a column in sample information in `colData`")} groups <- colDat[, group] if (nlevels(groups) != 3) stop(group, " does not have 3 levels") res <- lapply(levels(groups), function(i) { message(group, " = ", i) dds <- DESeq2::DESeqDataSetFromMatrix(counts[, groups == i], colDat[groups == i, ], design) dds <- DESeq2::DESeq(dds, ...) DESeq2::results(dds) }) setNames(res, levels(groups)) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/deseq_2x3.R
#' Convert 2x3 design DESeq2 objects to a volcano3d object #' #' This function is used instead of \code{\link{polar_coords}} if you have raw #' RNA-Seq count data. It takes results from a 2x3 design DESeq2 analysis using #' [deseq_2x3()]. Alternatively it will accept a list of 3 `DESeqDataSet` or #' `DESeqResults` objects each with the same type of binary comparison across 3 #' groups. Statistical results are extracted and converted to a 'volc3d' object, #' which can be directly plotted. Example usage would include comparing gene #' expression against a binary outcome e.g. response vs non-response, across 3 #' drugs. #' #' @param object A named list of 3 objects of class 'DESeqDataSet', or a list of #' 3 DESeq2 results dataframes generated by calling `DESeq2::results()`. Each #' object should contain the binary outcome comparison for each of the 3 #' groups, e.g. group A response vs non-response, group B response vs #' non-response, group C etc. The names of the groups are taken from the list #' names. #' @param pcutoff Cut-off for p-value significance #' @param fc_cutoff Cut-off for fold change on radial axis #' @param padj.method Can be `"qvalue"` or any method available in `p.adjust`. #' The option `"none"` is a pass-through. #' @param process Character value specifying colour process for statistical #' significant genes: "positive" specifies genes are coloured if fold change #' is >0; "negative" for genes with fold change <0 (note that for clarity the #' polar position is altered so that genes along each axis have the most #' strongly negative fold change values); or "two.sided" which is a compromise #' in which positive genes are labelled as before but genes with negative fold #' changes and significant p-values have an inverted colour scheme. #' @param scheme Vector of colours starting with non-significant genes/variables #' @param labs Optional character vector for labelling groups. Default `NULL` #' leads to abbreviated labels based on levels in `outcome` using #' [abbreviate()]. A vector of length 3 with custom abbreviated names for the #' outcome levels can be supplied. Otherwise a vector length 8 is expected, of #' the form "ns", "A+", "A+B+", "B+", "B+C+", "C+", "A+C+", "A+B+C+", where #' "ns" means non-significant and A, B, C refer to levels 1, 2, 3 in #' `outcome`, and must be in the correct order. #' @details #' This function generates a 'volc3d' class object for visualising a 2x3 way #' analysis for RNA-Seq data. For usual workflow it is typically preceded by a #' call to [deseq_2x3()] which runs the 3x DESeq2 analyses required. #' #' Scaled polar coordinates are based on the DESeq2 statistic for each group #' comparison. Unscaled polar coordinates are generated using the log2 fold #' change for each group comparison. #' #' The z axis for 3d volcano plots does not have as clear a corollary in 2x3 #' analysis as for the standard 3-way analysis (which uses the likelihood ratio #' test for the 3 groups). For 2x3 polar analysis the smallest p-value from the #' 3 group pairwise comparisons for each gene is used to generate a z coordinate #' as -log10(p-value). #' #' The colour scheme is not as straightforward as for the standard polar plot #' and volcano3D plot since genes (or attributes) can be significantly up or #' downregulated in the response comparison for each of the 3 groups. #' `process = "positive"` means that genes are labelled with colours if a gene #' is significantly upregulated in the response for that group. This uses the #' primary colours (RGB) so that if a gene is upregulated in both red and blue #' groups it becomes purple etc with secondary colours. If the gene is #' upregulated in all 3 groups it is labelled black. Non-significant genes are #' in grey. #' #' With `process = "negative"` genes are coloured when they are significantly #' downregulated. With `process = "two.sided"` the colour scheme means that both #' significantly up- and down-regulated genes are coloured with downregulated #' genes labelled with inverted colours (i.e. cyan is the inverse of red etc). #' However, significant upregulation in a group takes precedence. #' #' @return Returns an S4 'volc3d' object containing: #' \itemize{ #' \item{'df'} A list of 2 dataframes. Each dataframe contains both x,y,z #' coordinates as well as polar coordinates r, angle. The first dataframe has #' coordinates based on the DESeq2 statistic. The 2nd dataframe is unscaled #' and represents log2 fold change for gene expression. The `type` argument in #' \code{\link{volcano3D}}, \code{\link{radial_plotly}} and #' \code{\link{radial_ggplot}} corresponds to these dataframes. #' \item{'outcome'} An empty factor whose levels are the three-group contrast #' factor for comparisons #' \item{'data'} Empty dataframe for compatibility #' \item{'pvals'} A dataframe containing p-values. Columns 1-3 are pairwise #' comparisons between the outcome factor for groups A, B, C respectively. #' \item{'padj'} A dataframe containing p-values adjusted for multiple testing #' \item{'pcutoff} Numeric value for cut-off for p-value significance #' \item{'scheme'} Character vector with colour scheme for plotting #' \item{'labs'} Character vector with labels for colour groups #' } #' @seealso [deseq_2x3()] #' @importFrom Rfast rowMins #' @export deseq_2x3_polar <- function(object, pcutoff = 0.05, fc_cutoff = NULL, padj.method = "BH", process = c("positive", "negative", "two.sided"), scheme = c('grey60', 'red', 'gold2', 'green3', 'cyan', 'blue', 'purple', 'black'), labs = NULL) { if (length(object) != 3) stop("object must be a list of 3 DESeq2 results") if (!requireNamespace("DESeq2", quietly = TRUE)) { stop("Can't find package DESeq2. Try: BiocManager::install('DESeq2')", call. = FALSE) } if (is(object[[1]], "DESeqDataSet")) { if (!all.equal(object[[1]]@design, object[[3]]@design, object[[3]]@design)){ message("Design formulae differ")} } process <- match.arg(process) res <- lapply(object, function(i) { if (is(i, "DESeqDataSet")) { as.data.frame(DESeq2::results(i)) } else as.data.frame(i) }) rn <- Reduce(intersect, lapply(res, rownames)) df1 <- getCols(res, rn, 'stat') df2 <- getCols(res, rn, 'log2FoldChange') if (process == "negative") { df1 <- -df1 df2 <- -df2 } SE <- getCols(res, rn, 'lfcSE') colnames(SE) <- paste0("SE_", colnames(SE)) df1 <- cbind(df1, SE) df2 <- cbind(df2, SE) df1 <- polar_xy(df1) df2 <- polar_xy(df2) pvals <- getCols(res, rn, 'pvalue') if (padj.method != 'BH') { res[[1]]$padj <- deseq_qvalue(res[[1]], padj.method)$qvalue res[[2]]$padj <- deseq_qvalue(res[[2]], padj.method)$qvalue res[[3]]$padj <- deseq_qvalue(res[[3]], padj.method)$qvalue } padj <- getCols(res, rn, 'padj') outcome <- factor(levels = names(res)) ptab <- polar_p2x3(df2, pvals, padj, pcutoff, fc_cutoff, process, scheme, labs) df1 <- cbind(df1, ptab) df2 <- cbind(df2, ptab) methods::new("volc3d", df = list(scaled = df1, unscaled = df2, type = "deseq_2x3_polar"), outcome = outcome, data = data.frame(), pvals = pvals, padj = padj, pcutoff = pcutoff, scheme = scheme, labs = levels(ptab$lab)) } getCols <- function(res, rn, col) { out <- cbind(res[[1]][rn, col], res[[2]][rn, col], res[[3]][rn, col]) rownames(out) <- rn colnames(out) <- names(res) out } polar_p2x3 <- function(df, pvals, padj = pvals, pcutoff = 0.05, fc_cutoff = NULL, process = "positive", scheme = c('grey60', 'red', 'gold2', 'green3', 'cyan', 'blue', 'purple', 'black'), labs = NULL) { outcome_levels <- colnames(df)[1:3] pvalue <- Rfast::rowMins(pvals, value=TRUE) z <- -log10(pvalue) pcheck <- sapply(1:3, function(i) padj[,i] < pcutoff & df[,i] > 0) colnames(pcheck) <- outcome_levels pcheck <- pcheck *1 # convert to numeric pcheck[is.na(pcheck)] <- 0 # negatives if (process == "two.sided") { pneg <- sapply(1:3, function(i) padj[,i] < pcutoff & df[,i] < 0) colnames(pneg) <- outcome_levels negrs <- rowSums(pneg, na.rm=T) pneg[negrs>0] <- 1 - pneg[negrs>0] # invert pneg[is.na(pneg)] <- 0 posrs <- rowSums(pcheck, na.rm=T) # replace only grey points with pneg pcheck[posrs == 0, ] <- pneg[posrs == 0, ] } pset <- paste0(pcheck[,1], pcheck[,2], pcheck[,3]) if (!is.null(fc_cutoff)) { pset[df[, 'r'] < fc_cutoff] <- '000' } if (is.null(labs) | length(labs) == 3) { abbrev <- if (length(labs) == 3) labs else abbreviate(outcome_levels, 1) labs <- c("ns", paste0(abbrev[1], "+"), paste0(abbrev[1], "+", abbrev[2], "+"), paste0(abbrev[2], "+"), paste0(abbrev[2], "+", abbrev[3], "+"), paste0(abbrev[3], "+"), paste0(abbrev[1], "+", abbrev[3], "+"), paste0(abbrev[1], "+", abbrev[2], "+", abbrev[3], "+")) } lab <- factor(pset, levels = c('000', '100', '110', '010', '011', '001', '101', '111'), labels = labs) col <- scheme[lab] data.frame(z, pvalue, col, lab) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/deseq_2x3_polar.R
#' Convert DESeq2 objects to a volcano3d object #' #' This function is used instead of \code{\link{polar_coords}} if you have raw #' RNA-Seq count data. It takes 2 `DESeqDataSet` objects, extracts statistical #' results and converts the results to a 'volc3d' object, which can be directly #' plotted. #' #' @param object An object of class 'DESeqDataSet' with the full design formula. #' The function `DESeq` needs to have been run. #' @param objectLRT An object of class 'DESeqDataSet' with the reduced design #' formula. The function `DESeq` needs to have been run on this object with #' argument `test="LRT"`. #' @param contrast Character value specifying column within the metadata stored #' in the DESeq2 dataset objects is the outcome variable. This column must #' contain a factor with 3 levels. If not set, the function will select the #' last term in the design formula of `object` as per DESeq2 convention. #' @param data Optional matrix containing gene expression data. If not supplied, #' the function will pull the expression data from within the DESeq2 object #' using the DESeq2 function `assay()`. NOTE: for consistency with gene #' expression datasets, genes are in rows. #' @param pcutoff Cut-off for p-value significance #' @param padj.method Can be any method available in `p.adjust` or `"qvalue"`. #' The option `"none"` is a pass-through. #' @param filter_pairwise Logical whether adjusted p-value pairwise statistical #' tests are only conducted on genes which reach significant adjusted p-value #' cut-off on the group likelihood ratio test #' @param ... Optional arguments passed to \code{\link{polar_coords}} #' @return Calls \code{\link{polar_coords}} to return an S4 'volc3d' object #' @seealso \code{\link{polar_coords}}, \code{\link{voom_polar}}, #' \code{\link[DESeq2:DESeq]{DESeq}} in the DESeq2 package #' @examples #' #' \donttest{ #' library(DESeq2) #' #' counts <- matrix(rnbinom(n=1500, mu=100, size=1/0.5), ncol=15) #' cond <- factor(rep(1:3, each=5), labels = c('A', 'B', 'C')) #' #' # object construction #' dds <- DESeqDataSetFromMatrix(counts, DataFrame(cond), ~ cond) #' #' # standard analysis #' dds <- DESeq(dds) #' #' # Likelihood ratio test #' ddsLRT <- DESeq(dds, test="LRT", reduced= ~ 1) #' #' polar <- deseq_polar(dds, ddsLRT, "cond") #' volcano3D(polar) #' radial_ggplot(polar) #' } #' #' @export deseq_polar <- function(object, objectLRT, contrast = NULL, data = NULL, pcutoff = 0.05, padj.method = "BH", filter_pairwise = TRUE, ...) { # Check packages and input data if (!requireNamespace("DESeq2", quietly = TRUE)) { stop("Can't find package DESeq2. Try: BiocManager::install('DESeq2')", call. = FALSE) } if (!inherits(object, "DESeqDataSet")) stop("Not a DESeqDataSet object") if (!inherits(objectLRT, "DESeqDataSet")) stop("Not a DESeqDataSet object") termsDE <- attr(terms(DESeq2::design(object)), "term.labels") termsLRT <- attr(terms(DESeq2::design(objectLRT)), "term.labels") if (!setequal(termsDE, termsLRT)) message("Different full design formulae") if (is.null(contrast)) { contrast <- termsDE[length(termsDE)] message("Setting contrast to `", contrast, "`") } outcome <- object@colData[, contrast] if (nlevels(outcome) != 3) stop("Outcome does not have 3 levels") # Group statistics LRT <- DESeq2::results(objectLRT) LRT <- as.data.frame(LRT[, c('pvalue', 'padj')]) if (padj.method == "qvalue") { LRT <- deseq_qvalue(LRT) index <- if (filter_pairwise) { LRT$qvalue < pcutoff & !is.na(LRT$qvalue) } else !is.na(LRT$qvalue) ptype <- "qvalue" } else { index <- if (filter_pairwise) { LRT$padj < pcutoff & !is.na(LRT$padj) } else !is.na(LRT$padj) ptype <- "padj" } groups <- levels(outcome) contrastlist <- list(groups[1:2], groups[c(3, 1)], groups[2:3]) # Pairwise statistics pairres <- lapply(contrastlist, function(i) { res <- DESeq2::results(object, contrast = c(contrast, i)) as.data.frame(res[, c('pvalue', 'padj')]) }) pvals <- cbind(LRT[, "pvalue"], pairres[[1]][, "pvalue"], pairres[[2]][, "pvalue"], pairres[[3]][, "pvalue"]) pairadj <- lapply(pairres, function(res) { out <- rep_len(NA, nrow(LRT)) out[index] <- if (padj.method == "qvalue") { deseq_qvalue(res[index, ])$qvalue } else p.adjust(res[index, 'pvalue'], method = padj.method) out }) padj <- cbind(LRT[, ptype], pairadj[[1]], pairadj[[2]], pairadj[[3]]) dimnames(pvals) <- dimnames(padj) <- list(rownames(LRT), c("LRT", "AvB", "AvC", "BvC")) # Extract expression data if (is.null(data)) { vstdata <- if (nrow(object) < 1000) { DESeq2::varianceStabilizingTransformation(object) } else DESeq2::vst(object) if (!requireNamespace("SummarizedExperiment", quietly = TRUE)) { stop("Can't find package SummarizedExperiment. Try: BiocManager::install('SummarizedExperiment')", call. = FALSE) } data <- SummarizedExperiment::assay(vstdata) } out <- polar_coords(outcome, t(data), pvals, padj, pcutoff, ...) out@df$type <- "deseq_polar" out } deseq_qvalue <- function(df, method = "qvalue") { q <- qval(df$pvalue[!is.na(df$padj)], method) df$qvalue <- 1 # NA converted to 1 df$qvalue[!is.na(df$padj)] <- q df }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/deseq_polar.R
#' PEAC synovial sample data #' #' A dataset containing sample data for 81 synovial biopsies from the PEAC #' cohort #' #' @format A data frame with 81 rows and 1 variables: #' \describe{ #' \item{Pathotype}{The synovial biopsy histological pathotype} #' } #' @source \url{https://pubmed.ncbi.nlm.nih.gov/31461658/ #' } "syn_example_meta" #' PEAC synovial gene expression data #' #' A dataset containing the gene expression data for 81 synovial biopsies from #' the PEAC cohort #' #' @format A data frame with 500 rows representing the most significant #' genes/probes and 81 columns representing samples. #' @source \url{https://pubmed.ncbi.nlm.nih.gov/31461658/ #' } "syn_example_rld"
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/example_data.R
#' Forest plot individual gene from 2x3 factor analysis #' #' Forest plot individual gene from 2x3 factor analysis using either base #' graphics, plotly or ggplot2. #' #' @param object A 'volc3d' class object from a 2x3 analysis generated by #' [deseq_2x3_polar()] #' @param genes Vector of genes to plot #' @param scheme Vector of 3 colours for plotting #' @param labs Optional character vector of labels for the groups #' @param error_type Either "ci" or "se" to specify whether error bars use 95% #' confidence intervals or standard error #' @param error_width Width of error bars #' @param facet Logical whether to use facets for individual genes (ggplot2 #' only) #' @param gap Size of gap between groupings for each gene #' @param transpose Logical whether to transpose the plot #' @param mar Vector of margins on four sides. See [par()] #' @param ... Optional arguments #' @return Returns a plot using either base graphics (`forest_plot`), plotly #' (`forest_plotly`) or ggplot2 (`forest_ggplot`). `forest_plot` also #' invisibly returns the dataframe used for plotting. #' @seealso [deseq_2x3_polar()] #' @importFrom graphics abline arrows axis legend par points text #' @export forest_plot <- function(object, genes, scheme = c('red', 'green3', 'blue'), labs = NULL, error_type = c("ci", "se"), error_width = 0.05, gap = 1, transpose = FALSE, mar = if (transpose) c(5, 7, 5, 4) else c(5, 5, 5, 3), ...) { error_type <- match.arg(error_type) data <- forest_df(object, genes, labs, error_type, gap) xrange <- range(c(data$val-data$CI, data$val+data$CI, 0), na.rm=TRUE) prange <- range(data$pos) op <- par(mar=mar) on.exit(par(op)) new.args <- list(...) if (transpose) { plot.args <- list(x = NA, xlim = xrange, ylim = prange, yaxt="n", bty = "n", xlab = bquote("log"[2]~"FC"), ylab = "") if (length(new.args)) plot.args[names(new.args)] <- new.args do.call("plot", plot.args) arrows(data$val-data$CI, data$pos, data$val+data$CI, code=3, angle=90, length=error_width, col=scheme) points(data$val, y = data$pos, pch=19, col=scheme) abline(v = 0, lty = 2) axis(2, data$pos, data$labs, tick = FALSE, las = 1) axis(2, data$pos[seq_along(genes)*3-1], genes, tick = FALSE, line=2, las=1) text(xrange[2]+ diff(xrange)*0.06, data$pos, data$stars, xpd = NA) } else { plot.args <- list(x = NA, ylim = xrange, xlim = prange, xaxt="n", bty = "n", ylab = bquote("log"[2]~"FC"), xlab = "", las = 1) if (length(new.args)) plot.args[names(new.args)] <- new.args do.call("plot", plot.args) arrows(data$pos, data$val-data$CI, y1 = data$val+data$CI, code=3, angle=90, length=error_width, col=scheme) points(data$pos, data$val, pch=19, col=scheme) abline(h = 0, lty = 2) axis(1, data$pos, data$labs, tick = FALSE, las = 1) axis(1, data$pos[seq_along(genes)*3-1], genes, tick = FALSE, line=2) text(data$pos, xrange[2]+ diff(xrange)*0.06, data$stars, xpd = NA) } legend("topright", legend=colnames(object@df[[2]])[1:3], pch=19, col=scheme, bty="n", cex=0.8, inset = c(0,-0.25), xpd = NA) invisible(data) } #' @rdname forest_plot #' @export forest_plotly <- function(object, genes, scheme = c('red', 'green3', 'blue'), labs = NULL, error_type = c("ci", "se"), error_width = 4, gap = 1, transpose = FALSE, ...) { error_type <- match.arg(error_type) data <- forest_df(object, genes, labs, error_type, gap) if (transpose) { annot <- list(y = data$pos, x = max(data$val+data$CI, na.rm = TRUE), text = data$stars, showarrow = FALSE, xanchor='left') plot_ly(data = data, x = ~val, y = ~pos, colors = scheme, color = ~labs, type = 'scatter', mode = 'markers', error_x = list(array = ~CI, color = ~labs, width = error_width), ...) %>% layout(xaxis = list(title = "log<sub>2</sub> FC"), yaxis = list(title = "", ticktext = genes, tickvals = data$pos[seq_along(genes)*3-1]), annotations = annot) } else { annot <- list(x = data$pos, y = max(data$val+data$CI, na.rm = TRUE), text = data$stars, showarrow = FALSE, yanchor='bottom') plot_ly(data = data, y = ~val, x = ~pos, colors = scheme, color = ~labs, type = 'scatter', mode = 'markers', error_y = list(array = ~CI, color = ~labs, width = error_width), ...) %>% layout(yaxis = list(title = "log<sub>2</sub> FC"), xaxis = list(title = "", ticktext = genes, tickvals = data$pos[seq_along(genes)*3-1]), annotations = annot) } } #' @rdname forest_plot #' @importFrom ggplot2 geom_errorbar geom_vline geom_hline scale_x_continuous #' scale_y_continuous theme_minimal xlab ylab facet_grid expand_limits #' theme_bw element_line #' @importFrom rlang .data #' @export forest_ggplot <- function(object, genes, scheme = c('red', 'green3', 'blue'), labs = NULL, error_type = c("ci", "se"), error_width = 0.3, facet = TRUE, gap = 1, transpose = FALSE, ...) { error_type <- match.arg(error_type) data <- forest_df(object, genes, labs, error_type, gap) vdiff <- diff(range(c(data$val-data$CI, data$val+data$CI, 0), na.rm=TRUE)) if (facet) { if (transpose) { xmax <- max(data$val + data$CI, na.rm=TRUE) ggplot(data, aes(y=.data$labs, x=.data$val, color=.data$labs)) + geom_vline(xintercept = 0, linetype = "dashed", colour = "grey40") + geom_errorbar(aes(xmin=.data$val-.data$CI, xmax=.data$val+.data$CI), width=error_width) + geom_point() + scale_color_manual(values = scheme) + facet_grid(gene ~ .) + xlab(bquote("log"[2]~"FC")) + ylab("") + labs(color = "") + geom_text(y = data$labs, x = xmax +vdiff*0.05, colour = "black", label = data$stars, show.legend = FALSE) + expand_limits(x= xmax + vdiff * 0.04) + theme_bw() + theme(axis.text = element_text(colour = "black"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.spacing = unit(0, "cm"), strip.background = element_rect(fill="grey90")) } else { # not transposed ymax <- max(data$val + data$CI, na.rm=TRUE) ggplot(data, aes(x=.data$labs, y=.data$val, color=.data$labs)) + geom_hline(yintercept = 0, linetype = "dashed", colour = "grey40") + geom_errorbar(aes(ymin=.data$val-.data$CI, ymax=.data$val+.data$CI), width=error_width) + geom_point() + scale_color_manual(values = scheme) + facet_grid(. ~ gene) + ylab(bquote("log"[2]~"FC")) + xlab("") + labs(color = "") + geom_text(x = data$labs, y = ymax +vdiff*0.04, colour = "black", label = data$stars, show.legend = FALSE) + expand_limits(y= ymax + vdiff * 0.04) + theme_bw() + theme(axis.text = element_text(colour = "black"), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.spacing = unit(0, "cm"), strip.background = element_rect(colour=NA, fill=NA)) } } else { # single plot, no facets if (transpose) { ggplot(data, aes(y=.data$pos, x=.data$val, color=.data$labs)) + geom_errorbar(aes(xmin=.data$val-.data$CI, xmax=.data$val+.data$CI), width=error_width) + geom_point() + scale_color_manual(values = scheme) + xlab(bquote("log"[2]~"FC")) + ylab("") + labs(color = "") + scale_y_continuous(breaks=data$pos[seq_along(genes)*3-1], labels=genes) + geom_vline(xintercept = 0, linetype = "dashed") + annotate(geom = "text", y = data$pos, x = max(data$val + data$CI, na.rm=TRUE) +vdiff*0.05, label = data$stars) + theme_minimal() + theme(axis.text = element_text(colour = "black"), axis.line.x = element_line(color="black")) } else { ggplot(data, aes(x=.data$pos, y=.data$val, color=.data$labs)) + geom_errorbar(aes(ymin=.data$val-.data$CI, ymax=.data$val+.data$CI), width=error_width) + geom_point() + scale_color_manual(values = scheme) + ylab(bquote("log"[2]~"FC")) + xlab("") + labs(color = "") + scale_x_continuous(breaks=data$pos[seq_along(genes)*3-1], labels=genes) + geom_hline(yintercept = 0, linetype = "dashed") + annotate(geom = "text", x = data$pos, y = max(data$val + data$CI, na.rm=TRUE) +vdiff*0.03, label = data$stars) + theme_minimal() + theme(axis.text = element_text(colour = "black"), axis.line.y = element_line(color="black")) } } } forest_df <- function(object, genes, labs = NULL, error_type = "ci", gap = 1) { if(! is(object, "volc3d")) stop("Not a 'volc3d' class object") if(!object@df$type %in% c("polar_coords_2x3", "deseq_2x3_polar")) { stop("Not a 2x3-way analysis") } df <- object@df[[2]] val <- as.vector(t(df[genes, 1:3])) CI <- as.vector(t(df[genes, 4:6])) if (error_type == "ci") CI <- CI * 1.96 ngenes <- length(genes) pos <- rep.int(1:3, ngenes) + rep(seq(from=0, by=3+gap, length.out=ngenes), each = 3) if (is.null(labs)) labs <- abbreviate(colnames(df)[1:3], 3) pval <- as.vector(t(object@padj[genes,])) data <- data.frame(gene = factor(rep(genes, each = 3), levels = genes), labs = factor(rep_len(1:3, 3*ngenes), labels = labs), pos = pos, val = val, CI = CI, pval = pval, stars = stars.pval(pval)) data } # code modified from orphaned package gtools #' @importFrom stats symnum stars.pval <- function(p.value) { unclass( symnum(p.value, corr = FALSE, na = FALSE, cutpoints = c(0, 0.001, 0.01, 0.05, 1), symbols = c("***", "**", "*", "") ) ) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/forest_plot.R
setClassUnion("df_or_matrix", c("data.frame", "matrix")) #' An S4 class to define the polar coordinates. #' #' @slot df List of coordinate data frames for scaled and unscaled expression #' @slot outcome Outcome vector #' @slot data Expression data #' @slot pvals Matrix or dataframe with p-values #' @slot padj Matrix adjusted p-values #' @slot pcutoff Cut-off for p-value significance #' @slot scheme Vector for colour scheme #' @slot labs Character vector for labelling groups setClass("volc3d", slots = list(df = "list", outcome = "factor", data = "df_or_matrix", pvals = "matrix", padj = "df_or_matrix", pcutoff = "numeric", scheme = "character", labs = "character")) #' Coordinates for Three Way Polar Plot #' #' This function creates a 'volc3d' object of S4 class for downstream plots #' containing the p-values from a three-way group comparison, expression data #' sample data and polar coordinates. For RNA-Seq count data, two functions #' \code{\link{deseq_polar}} or \code{\link{voom_polar}} can be used instead. #' #' @param outcome Outcome vector with 3 groups, ideally as a factor. If it is #' not a factor, this will be coerced to a factor. This must have exactly 3 #' levels. NOTE: if `pvals` is given, the order of the levels in `outcome` #' must correspond to the order of columns in `pvals`. #' @param data Dataframe or matrix with variables in columns #' @param pvals Matrix or dataframe with p-values. The first column represents a #' test across all 3 categories such as one-way ANOVA or likelihood ratio #' test. Columns 2-4 represent pairwise tests comparing groups A vs B, A vs C #' and B vs C, where A, B, C represent levels 1, 2, 3 in `outcome`. Columns #' 2-4 must be provided in the correct order. If `pvals` is not given, it is #' calculated using the function \code{\link{calc_pvals}}. #' @param padj Matrix or dataframe with adjusted p-values. If not supplied, #' defaults to use nominal p-values from `pvals`. #' @param pcutoff Cut-off for p-value significance #' @param fc_cutoff Cut-off for fold change on radial axis #' @param scheme Vector of colours starting with non-significant variables #' @param labs Optional character vector for labelling groups. Default `NULL` #' leads to abbreviated labels based on levels in `outcome` using #' [abbreviate()]. A vector of length 3 with custom abbreviated names for the #' outcome levels can be supplied. Otherwise a vector length 7 is expected, of #' the form "ns", "B+", "B+C+", "C+", "A+C+", "A+", "A+B+", where "ns" means #' non-significant and A, B, C refer to levels 1, 2, 3 in `outcome`, and must #' be in the correct order. #' @param ... Optional arguments passed to \code{\link{calc_pvals}} #' #' @return Returns an S4 'volc3d' object containing: #' \itemize{ #' \item{'df'} A list of 2 dataframes. Each dataframe contains both x,y,z #' coordinates as well as polar coordinates r, angle. The first dataframe has #' coordinates on scaled data. The 2nd dataframe has unscaled data (e.g. log2 #' fold change for gene expression). The `type` argument in #' \code{\link{volcano3D}}, \code{\link{radial_plotly}} and #' \code{\link{radial_ggplot}} corresponds to these dataframes. #' \item{'outcome'} The three-group contrast factor used for comparisons #' \item{'data'} Dataframe or matrix containing the expression data #' \item{'pvals'} A dataframe containing p-values. First column is the 3-way #' comparison (LRT or ANOVA). Columns 2-4 are pairwise comparisons between #' groups A vs B, A vs C and B vs C, where A, B, C are the 3 levels in the #' outcome factor. #' \item{'padj'} A dataframe containing p-values adjusted for multiple testing #' \item{'pcutoff} Numeric value for cut-off for p-value significance #' \item{'scheme'} Character vector with colour scheme for plotting #' \item{'labs'} Character vector with labels for colour groups #' } #' #' @seealso \code{\link{deseq_polar}}, \code{\link{voom_polar}}, #' \code{\link{calc_pvals}} #' @examples #' data(example_data) #' syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, #' data = t(syn_example_rld)) #' #' @importFrom methods is #' @export #' polar_coords <- function( outcome, data, pvals = NULL, padj = pvals, pcutoff = 0.05, fc_cutoff = NULL, scheme = c('grey60', 'red', 'gold2', 'green3', 'cyan', 'blue', 'purple'), labs = NULL, ...) { # Run checks on input data if (length(outcome) != nrow(data)) { stop("Number of rows in `data` differs from `outcome`")} if (any(is.na(outcome))) { ok <- !is.na(outcome) data <- data[ok,] outcome <- outcome[ok] message("Removing NA from `outcome`") } outcome <- as.factor(outcome) outcome <- droplevels(outcome) if (nlevels(outcome) != 3) stop("`outcome` must have 3 levels") data <- as.matrix(data) # Scale data and calculate mean expression for each group data_sc <- scale(data) df1 <- vapply(levels(outcome), function(i) { colMeans(data_sc[outcome == i, ], na.rm = TRUE)}, numeric(ncol(data))) df2 <- vapply(levels(outcome), function(i) { colMeans(data[outcome == i, ], na.rm = TRUE)}, numeric(ncol(data))) # Transform to polar coordinates df1 <- polar_xy(df1) df2 <- polar_xy(df2) # Calculate p-values if not provided if (is.null(pvals)) { pv <- calc_pvals(outcome, data, pcutoff, ...) pvals <- pv$pvals padj <- pv$padj } # Assign significance groupings ptab <- polar_p(outcome, df2, pvals, padj, pcutoff, fc_cutoff, scheme, labs) df1 <- cbind(df1, ptab) df2 <- cbind(df2, ptab) # Output final object methods::new("volc3d", df = list(scaled = df1, unscaled = df2, type = "polar_coords"), outcome = outcome, data = data, pvals = pvals, padj = padj, pcutoff = pcutoff, scheme = scheme, labs = levels(ptab$lab)) } # Calculate polar coordinates from expression data polar_xy <- function(df, angle_offset = 0) { y <- sinpi(1/3) * (df[,2] - df[,3]) x <- df[,1] - (cospi(1/3) * (df[,3] + df[,2])) r <- sqrt(x^2 + y^2) angle <- atan2(y, x)/(2*pi) angle <- ((angle + angle_offset) %% 1) * 360 cbind(df, x, y, r, angle) } #' Calculate one-way test and pairwise tests #' #' Internal function for calculating 3-class group test (either one-way ANOVA or #' Kruskal-Wallis test) and pairwise tests (either t-test or Wilcoxon test) on #' multi-column data against an outcome parameter with 3 levels. #' #' @param outcome Outcome vector with 3 groups, ideally as a factor. If it is #' not a factor, this will be coerced to a factor. This must have exactly 3 #' levels. #' @param data Dataframe or matrix with variables in columns #' @param pcutoff Cut-off for p-value significance #' @param padj.method Can be any method available in `p.adjust` or `"qvalue"`. #' The option "none" is a pass-through. #' @param group_test Specifies statistical test for 3-class group comparison. #' "anova" means one-way ANOVA, "kruskal.test" means Kruskal-Wallis test. #' @param pairwise_test Specifies statistical test for pairwise comparisons #' @param exact Logical which is only used with `pairwise_test = "wilcoxon"` #' @param filter_pairwise Logical. If `TRUE` (the default) p-value adjustment on #' pairwise statistical tests is only conducted on attributes which reached #' the threshold for significance after p-value adjustment on the group #' statistical test. #' @importFrom Rfast ftests ttests kruskaltests #' @importFrom matrixTests row_wilcoxon_twosample #' @return Returns a list with first element representing a data frame of #' unadjusted p-values and the second element adjusted p-values. Each dataframe #' contains 4 columns: the first column is the 3-way comparison (LRT or ANOVA). #' Columns 2-4 are pairwise comparisons between groups A vs B, A vs C and #' B vs C, where A, B, C are the 3 levels in the outcome factor. #' @export #' calc_pvals <- function(outcome, data, pcutoff = 0.05, padj.method = "BH", group_test = c("anova", "kruskal.test"), pairwise_test = c("t.test", "wilcoxon"), exact = FALSE, filter_pairwise = TRUE) { # Structure and check input data group_test <- match.arg(group_test) pairwise_test <- match.arg(pairwise_test) outcome <- as.factor(outcome) if (nlevels(outcome) != 3) stop("`outcome` must have 3 levels") data <- as.matrix(data) # Perform group statistical tests res <- switch(group_test, "anova" = Rfast::ftests(data, outcome), "kruskal.test" = Rfast::kruskaltests(data, outcome)) rownames(res) <- colnames(data) onewayp <- res[, 2] # Perform pairwise statistical tests indx <- lapply(levels(outcome), function(i) outcome == i) if (pairwise_test == "wilcoxon") { res1 <- suppressWarnings( matrixTests::row_wilcoxon_twosample(t(data[indx[[1]], ]), t(data[indx[[2]], ]), exact = exact)) res2 <- suppressWarnings( matrixTests::row_wilcoxon_twosample(t(data[indx[[1]], ]), t(data[indx[[3]], ]), exact = exact)) res3 <- suppressWarnings( matrixTests::row_wilcoxon_twosample(t(data[indx[[2]], ]), t(data[indx[[3]], ]), exact = exact)) } else { res1 <- Rfast::ttests(data[indx[[1]], ], data[indx[[2]], ]) res2 <- Rfast::ttests(data[indx[[1]], ], data[indx[[3]], ]) res3 <- Rfast::ttests(data[indx[[2]], ], data[indx[[3]], ]) } p1 <- res1[, "pvalue"] p2 <- res2[, "pvalue"] p3 <- res3[, "pvalue"] pvals <- cbind(onewayp, p1, p2, p3) # Perform correction for multiple testing, optional if (padj.method == "none") { padj <- pvals } else { onewaypadj <- qval(onewayp, method = padj.method) index <- if (filter_pairwise) { onewaypadj < pcutoff & !is.na(onewaypadj) } else !is.na(onewaypadj) padj <- data.frame(onewaypadj, p1 = NA, p2 = NA, p3 = NA) padj$p1[index] <- qval(p1[index], method = padj.method) padj$p2[index] <- qval(p2[index], method = padj.method) padj$p3[index] <- qval(p3[index], method = padj.method) } padj <- as.matrix(padj) list(pvals = pvals, padj = padj) } # Perform correction for multiple testing #' @importFrom stats p.adjust p.adjust.methods #' qval <- function(p, method = "qvalue") { if (method %in% p.adjust.methods) return(p.adjust(p, method = method)) # For qvalue, check if installed if (!requireNamespace("qvalue", quietly = TRUE)) { stop("Can't find package qvalue. Try: BiocManager::install('qvalue')", call. = FALSE) } q <- try(qvalue::qvalue(p)$qvalues, silent = TRUE) if (inherits(q, 'try-error')) q <- p.adjust(p, method = "BH") q } # Assign grouping based on pairwise and group significance #' @importFrom Rfast rowMins #' polar_p <- function(outcome, df2, pvals, padj = pvals, pcutoff = 0.05, fc_cutoff = NULL, scheme = c('grey60', 'red', 'gold2', 'green3', 'cyan', 'blue', 'purple'), labs = NULL) { # Check pairwise significance by cutoff pvalue <- pvals[,1] z <- -log10(pvals[,1]) paircut <- padj[, 2:4] < pcutoff paircut <- paircut *1 # convert matrix to numeric # Find the downregulated group mincol <- Rfast::rowMins(as.matrix(df2[, 1:3])) mincol2 <- c("A", "B", "C")[mincol] pairmerge <- paste0(mincol2, paircut[,1], paircut[,2], paircut[,3]) pgroup <- rep_len(1, nrow(df2)) # Assign groups depending on pairwise significance: sequence AB, AC, BC pgroup[grep("A10.|C.01", pairmerge)] <- 2 # default red pgroup[grep("A01.|B0.1", pairmerge)] <- 4 # default green pgroup[grep("B1.0|C.10", pairmerge)] <- 6 # default blue pgroup[grep("A11.", pairmerge)] <- 3 # default yellow pgroup[grep("B1.1", pairmerge)] <- 5 # default cyan pgroup[grep("C.11", pairmerge)] <- 7 # default purple pgroup[pvals[ ,1] > pcutoff] <- 1 # not significant for all p_group > cutoff if (!is.null(fc_cutoff)) { pgroup[df2[, 'r'] < fc_cutoff] <- 1 } col <- scheme[pgroup] # Label the groups by upregulation if (is.null(labs) | length(labs) == 3) { abbrev <- if (length(labs) == 3) labs else abbreviate(levels(outcome), 1) labs <- c("ns", paste0(abbrev[2], "+"), paste0(abbrev[2], "+", abbrev[3], "+"), paste0(abbrev[3], "+"), paste0(abbrev[1], "+", abbrev[3], "+"), paste0(abbrev[1], "+"), paste0(abbrev[1], "+", abbrev[2], "+")) } lab <- factor(pgroup, levels = 1:7, labels = labs) data.frame(z, pvalue, col, lab) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/polar_coords.R
#' Coordinates for three way polar plot from 2x3 factor analysis #' #' This function creates a 'volc3d' object of S4 class for downstream plots #' containing the p-values from a 2x3 factor analysis, expression data #' sample data and polar coordinates. For RNA-Seq count data, two functions #' \code{\link{deseq_2x3}} followed by [deseq_2x3_polar()] can be used instead. #' #' @param data Dataframe or matrix with variables in columns and samples in rows #' @param metadata Dataframe of sample information with samples in rows #' @param outcome Either the name of column in `metadata` containing the binary #' outcome data. Or a vector with 2 groups, ideally a factor. If it is not a #' factor, this will be coerced to a factor. This must have exactly 2 levels. #' @param group Either the name of column in `metadata` containing the 3-way #' grouping data. Or a vector with 3 groups, ideally a factor. If it is not a #' factor, this will be coerced to a factor. This must have exactly 3 levels. #' NOTE: if `pvals` is given, the order of the levels in `group` must #' correspond to the order of columns in `pvals`. #' @param pvals Optional matrix or dataframe with p-values in 3 columns. If #' `pvals` is not given, it is calculated using the function #' \code{\link{calc_stats_2x3}}. The p-values in 3 columns represent the #' comparison between the binary outcome with each column for the 3 groups as #' specified in `group`. #' @param padj Matrix or dataframe with adjusted p-values. If not supplied, #' defaults to use nominal p-values from `pvals`. #' @param pcutoff Cut-off for p-value significance #' @param fc_cutoff Cut-off for fold change on radial axis #' @param padj.method Can be `"qvalue"` or any method available in `p.adjust`. #' The option `"none"` is a pass-through. #' @param process Character value specifying colour process for statistical #' significant genes: "positive" specifies genes are coloured if fold change #' is >0; "negative" for genes with fold change <0 (note that for clarity the #' polar position is altered so that genes along each axis have the most #' strongly negative fold change values); or "two.sided" which is a compromise #' in which positive genes are labelled as before but genes with negative fold #' changes and significant p-values have an inverted colour scheme. #' @param scheme Vector of colours starting with non-significant variables #' @param labs Optional character vector for labelling groups. Default `NULL` #' leads to abbreviated labels based on levels in `outcome` using #' [abbreviate()]. A vector of length 3 with custom abbreviated names for the #' outcome levels can be supplied. Otherwise a vector length 8 is expected, of #' the form "ns", "A+", "A+B+", "B+", "B+C+", "C+", "A+C+", "A+B+C+", where #' "ns" means non-significant and A, B, C refer to levels 1, 2, 3 in #' `outcome`, and must be in the correct order. #' @param ... Optional arguments passed to \code{\link{calc_stats_2x3}} #' @details #' This function is designed for manually generating a 'volc3d' class object for #' visualising a 2x3 way analysis comparing a large number of attributes such as #' genes. For RNA-Seq data we suggest using [deseq_2x3()] and #' [deseq_2x3_polar()] functions in sequence instead. #' #' Scaled polar coordinates are generated using the t-score for each group #' comparison. Unscaled polar coordinates are generated as difference between #' means for each group comparison. If p-values are not supplied they are #' calculated by [calc_stats_2x3()] using either t-tests or wilcoxon tests. #' #' The z axis for 3d volcano plots does not have as clear a corollary in 2x3 #' analysis as for the standard 3-way analysis (which uses the likelihood ratio #' test for the 3 groups). For 2x3 polar analysis the smallest p-value from the #' 3 group pairwise comparisons for each gene is used to generate a z coordinate #' as -log10(p-value). #' #' The colour scheme is not as straightforward as for the standard polar plot #' and volcano3D plot since genes (or attributes) can be significantly up or #' downregulated in the response comparison for each of the 3 groups. #' `process = "positive"` means that genes are labelled with colours if a gene #' is significantly upregulated in the response for that group. This uses the #' primary colours (RGB) so that if a gene is upregulated in both red and blue #' group it becomes purple etc with secondary colours. If the gene is #' upregulated in all 3 groups it is labelled black. Non-significant genes are #' in grey. #' #' With `process = "negative"` genes are coloured when they are significantly #' downregulated. With `process = "two.sided"` the colour scheme means that both #' significantly up- and down-regulated genes are coloured with downregulated #' genes labelled with inverted colours (i.e. cyan is the inverse of red etc). #' However, significant upregulation in a group takes precedence. #' #' @return Returns an S4 'volc3d' object containing: #' \itemize{ #' \item{'df'} A list of 2 dataframes. Each dataframe contains both x,y,z #' coordinates as well as polar coordinates r, angle. The first dataframe has #' coordinates on scaled data. The 2nd dataframe has unscaled data (e.g. log2 #' fold change for gene expression). The `type` argument in #' \code{\link{volcano3D}}, \code{\link{radial_plotly}} and #' \code{\link{radial_ggplot}} corresponds to these dataframes. #' \item{'outcome'} The three-group contrast factor used for comparisons, #' linked to the `group` column #' \item{'data'} Dataframe or matrix containing the expression data #' \item{'pvals'} A dataframe containing p-values in 3 columns representing #' the binary comparison for the outcome for each of the 3 groups. #' \item{'padj'} A dataframe containing p-values adjusted for multiple testing #' \item{'pcutoff} Numeric value for cut-off for p-value significance #' \item{'scheme'} Character vector with colour scheme for plotting #' \item{'labs'} Character vector with labels for colour groups #' } #' #' @seealso \code{\link{deseq_2x3}}, \code{\link{deseq_2x3_polar}}, #' \code{\link{calc_stats_2x3}} #' @importFrom stats complete.cases #' @export polar_coords_2x3 <- function(data, metadata = NULL, outcome, group, pvals = NULL, padj = pvals, pcutoff = 0.05, fc_cutoff = NULL, padj.method = "BH", process = c("positive", "negative", "two.sided"), scheme = c('grey60', 'red', 'gold2', 'green3', 'cyan', 'blue', 'purple', 'black'), labs = NULL, ...) { process <- match.arg(process) if (!is.null(metadata)) { if (length(outcome) != 1 | !outcome %in% colnames(metadata)) { stop(outcome, " is not a column in metadata") } outcome <- factor(metadata[, outcome]) if (length(group) != 1 | !group %in% colnames(metadata)) { stop(group, " is not a column in metadata") } group <- factor(metadata[, group]) } if (!all.equal(nrow(data), length(outcome), length(group))) { stop("Mismatch between data and metadata") } if (nlevels(group) != 3) stop("Number of levels in group is not 3") if (nlevels(outcome) != 2) stop("Number of levels in outcome is not 2") if (any(is.na(outcome), is.na(group))) { ok <- complete.cases(outcome, group) data <- data[ok,] outcome <- outcome[ok] group <- group[ok] message("Removing NA from outcome/group") } res <- calc_stats_2x3(data, outcome, group, padj.method, ...) rn <- Reduce(intersect, lapply(res, rownames)) df1 <- getCols(res, rn, 'statistic') df2 <- getCols(res, rn, 'mean.diff') if (is.null(pvals)) { pvals <- getCols(res, rn, 'pvalue') padj <- getCols(res, rn, 'padj') } SE <- getCols(res, rn, 'stderr') colnames(SE) <- paste0("SE_", colnames(SE)) if (process == "negative") { df1 <- -df1 df2 <- -df2 } df1 <- cbind(df1, SE) df2 <- cbind(df2, SE) df1 <- polar_xy(df1) df2 <- polar_xy(df2) outcome <- factor(levels = levels(group)) ptab <- polar_p2x3(df2, pvals, padj, pcutoff, fc_cutoff, process, scheme, labs) df1 <- cbind(df1, ptab) df2 <- cbind(df2, ptab) methods::new("volc3d", df = list(scaled=df1, unscaled=df2, type="polar_coords_2x3"), outcome = outcome, data = data, pvals = pvals, padj = padj, pcutoff = pcutoff, scheme = scheme, labs = levels(ptab$lab)) } #' Calculate p-values for 2x3-way analysis #' #' @param data Dataframe or matrix with variables in columns and samples in rows #' @param outcome Factor with 2 levels #' @param group Factor with 3 levels #' @param padj.method Can be `"qvalue"` or any method available in `p.adjust`. #' The option `"none"` is a pass-through. #' @param test Character value specifying the statistical test between the 2 #' level response outcome. Current options are "t.test" or "wilcoxon". #' @param exact Logical for whether to use an exact test (Wilcoxon test only) #' @importFrom matrixTests col_t_welch col_wilcoxon_twosample #' @return A list containing a data frame with summary statistics for the #' comparisons between the outcome, for each group level. #' @export #' calc_stats_2x3 <- function(data, outcome, group, padj.method, test = c("t.test", "wilcoxon"), exact = FALSE) { test <- match.arg(test) res <- lapply(levels(group), function(i) { subdat <- data[group == i, ] suboutcome <- as.numeric(outcome[group == i]) out <- col_t_welch(subdat[suboutcome==1, ], subdat[suboutcome==2, ]) if (test == "wilcoxon") { out$pvalue <- col_wilcoxon_twosample(subdat[suboutcome==1, ], subdat[suboutcome==2, ], exact = exact)$pvalue } out$padj <- qval(out$pvalue, padj.method) out }) names(res) <- levels(group) res }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/polar_coords_2x3.R
setClassUnion("numeric_or_integer_or_NULL", c("numeric", "integer", "NULL")) #' An S4 class to define the polar grid coordinates system. #' #' @slot polar_grid The coordinates for the cylindrical grid segments with #' x,y,z coordinates #' @slot axes The axes features for 'plotly' #' @slot axis_labs The axis labels #' @slot r The grid radius #' @slot z The grid height #' @slot text_coords data frame for axis label cartesian coordinates (x, y, z) #' @slot n_r_breaks The number of ticks on the r axis #' @slot n_z_breaks The number of ticks on the z axis #' @slot r_breaks The r axis ticks as a numeric #' @slot z_breaks The z axis ticks as a numeric setClass("grid", slots = list( polar_grid = "data.frame", axes = "data.frame", axis_labs = "list", r = "numeric", z = "numeric", text_coords = "data.frame", n_r_breaks = "numeric_or_integer_or_NULL", n_z_breaks = "numeric_or_integer_or_NULL", r_breaks = "numeric_or_integer_or_NULL", z_breaks = "numeric_or_integer_or_NULL" )) #' Grid required for 3D volcano plot and 2D radial plots #' #' Generates a cylindrical grid of the appropriate dimensions for a 3D volcano #' plot #' @param r_vector An optional numerical vector for the radial coordinates. #' This is used to calculate breaks on the r axis using #' \code{\link[base]{pretty}}. If this is NULL the r_axis_ticks are used as #' breaks. #' @param z_vector An optional numerical vector for the z coordinates. #' This is used to calculate breaks on the z axis using \code{pretty}. If this #' is NULL the z_axis_ticks are used as breaks. #' @param r_axis_ticks A numerical vector of breaks for the radial axis (used #' if r_vector is NULL). #' @param z_axis_ticks A numerical vector of breaks for the z axis (used #' if z_vector is NULL). #' @param axis_angle angle in radians to position the radial axis #' (default = 5/6) #' @param n_spokes the number of outward spokes to be plotted (default = 12) #' @param axes_from_origin Whether the axis should start at 0 or the first #' break (default = TRUE) #' @param ... optional parameters for \code{\link[base]{pretty}} on the r axis #' @return Returns an S4 grid object containing: #' \itemize{ #' \item{'polar_grid'} The coordinates for a radial grid #' \item{'axes'} The axes features for 'plotly' #' \item{'axis_labels'} The axis labels #' \item{'r'} The grid radius #' \item{'z'} The grid height #' \item{'text_coords'} The coordinates for text labels #' \item{'n_r_breaks'} The number of ticks on the r axis #' \item{'n_r_breaks'} The number of ticks on the z axis #' } #' @references #' Lewis, Myles J., et al. (2019). #' \href{https://pubmed.ncbi.nlm.nih.gov/31461658/}{ #' Molecular portraits of early rheumatoid arthritis identify clinical and #' treatment response phenotypes.} #' \emph{Cell reports}, \strong{28}:9 #' @keywords dplot manip htest #' @export #' @examples #' data(example_data) #' syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, #' data = t(syn_example_rld)) #' #' grid <- polar_grid(r_vector=syn_polar@df[[1]]$r, #' z_vector=NULL, #' r_axis_ticks = NULL, #' z_axis_ticks = c(0, 8, 16, 32), #' n_spokes = 4) polar_grid <- function(r_vector = NULL, z_vector = NULL, r_axis_ticks = NULL, z_axis_ticks = NULL, axis_angle = 5/6, n_spokes = 12, axes_from_origin = TRUE, ...){ # Determine the radial axis breaks if(is.null(r_axis_ticks)) { r_breaks <- pretty(r_vector, ...) } else{ r_breaks <- r_axis_ticks} r_breaks <- r_breaks[! is.na(r_breaks)] r_breaks <- sort(r_breaks) if(r_breaks[1] != 0) r_breaks <- c(0, r_breaks) # Determine the z-axis breaks (for 3D volcano) if(is.null(z_axis_ticks)) { z_breaks <- pretty(z_vector) } else{ z_breaks <- z_axis_ticks } z_breaks <- z_breaks[! is.na(z_breaks)] z_breaks <- sort(z_breaks) if(length(z_breaks) > 0) { if( z_breaks[1] != 0) z_breaks <- c(0, z_breaks)} n_r_breaks <- length(r_breaks) - 1 n_z_breaks <- length(z_breaks) - 1 if(n_z_breaks < 0) { n_z_breaks <- 0 } # Set up the concentric circles on the x/y plane # (Circles split by NA to make discontinuous) cylindrical_grid <- data.frame( x = unlist(lapply(1:n_r_breaks, function(i){ c(max(r_breaks)/n_r_breaks*i*cospi(0:200/100), NA) })), y = unlist(lapply(1:n_r_breaks, function(i){ c(max(r_breaks)/n_r_breaks*i*sinpi(0:200/100), NA) })), z = 0, area = "cylindrical_grid") # radial spokes out mz <- switch(as.character(is.null(z_breaks)), "TRUE"=0, "FALSE"=max(z_breaks)) # The polar grid polar_grid_top <- data.frame( x = unlist(lapply(c(1:n_spokes), function(i){ c(max(r_breaks)/n_r_breaks*cospi(i*2/n_spokes), rep(max(r_breaks)*cospi(i*2/n_spokes), 2), NA) })), y = unlist(lapply(c(1:n_spokes), function(i){ c(max(r_breaks)/n_r_breaks*sinpi(i*2/n_spokes), rep(max(r_breaks)*sinpi(i*2/n_spokes), 2), NA) })), z = rep(c(0, 0, mz, NA), n_spokes), area = "polar grid top") # Create the circles on the cylinder - h/d cylinders z_cyl <- c() for (i in z_breaks[2:length(z_breaks)]){ z_cyl <- c(z_cyl, rep(i, 201), NA) } if(is.null(z_vector) & is.null(z_axis_ticks)){ cylinder <- NULL } else{ cylinder <- data.frame(x = rep(c(max(r_breaks)*cospi(0:200/100), NA), n_z_breaks), y = rep(c(max(r_breaks)*sinpi(0:200/100), NA), n_z_breaks), z = z_cyl, area = "cylinder") } # The cylindrical coordinates polar_grid <- rbind(polar_grid_top, cylindrical_grid, cylinder) # Add the three axes axis_start <- ifelse(axes_from_origin, 0, max(r_breaks)/n_r_breaks) axes <- data.frame( x = unlist(lapply(0:2, function(i) { c(axis_start * cospi(i * 2/3), rep(max(r_breaks) * cospi(i * 2/3), 2), NA) })), y = unlist(lapply(0:2, function(i) { c(axis_start * sinpi(i * 2/3), rep(max(r_breaks) * sinpi(i * 2/3), 2), NA) })), z = rep(c(0, 0, mz, NA), 3)) radial_spokes <- data.frame(x = rep(0,3), y = rep(0,3), xend = cospi(0:2 * 2/3), yend = sinpi(0:2 * 2/3)) # Label the axes axis_labs <- data.frame(x = radial_spokes$xend*max(r_breaks), y = radial_spokes$yend*(max(r_breaks)) ) axis_labs$x_adjust <- unlist(lapply(sign(axis_labs$x), function(s) { switch(as.character(s), "1" = "right", "-1" = "left", "0" = "center") })) axis_labs$y_adjust <- unlist(lapply(sign(axis_labs$y), function(s) { switch(as.character(s), "1" = "top", "-1" = "bottom", "0" = "middle") })) axis_labs$adjust <- paste(axis_labs$y_adjust, axis_labs$x_adjust) text_coords <- data.frame(x = r_breaks[2:length(r_breaks)]*sinpi(axis_angle), y = r_breaks[2:length(r_breaks)]*cospi(axis_angle), text = format(r_breaks[2:length(r_breaks)], digits = 2)) # Output as a grid object methods::new("grid", polar_grid = polar_grid, axes = axes, axis_labs = axis_labs, r = max(r_breaks), z = mz, text_coords = text_coords, n_r_breaks = n_r_breaks, n_z_breaks = n_z_breaks, r_breaks = r_breaks[2:length(r_breaks)], z_breaks = z_breaks[2:length(z_breaks)]) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/polar_grid.R
#' 'Ggplot' for Three Way Polar Plot #' #' This function creates a 3-way polar plot using 'ggplot' for a three-class #' comparison. #' #' @param polar A 'volc3d' object with the p-values between groups of interest #' and polar coordinates created by \code{\link{polar_coords}}, #' \code{\link{deseq_polar}} or \code{\link{voom_polar}}. #' @param type Numeric value whether to use scaled (z-score) or unscaled (fold #' change) as magnitude. Options are 1 = z-score (default) or 2 = #' unscaled/fold change. #' @param colours A vector of colours for the non-significant points and each of #' the six groups. #' @param label_rows A vector of row names or indices to label #' @param arrow_length The length of label arrows #' @param label_size Font size of labels/annotations (default = 5). #' @param colour_code_labels Logical whether label annotations should be colour #' coded. If FALSE `label_colour` is used. #' @param label_colour Colour of annotation labels if not colour coded #' @param grid_colour The colour of the grid (default="grey80") #' @param grid_width The width of the axis lines (default=0.6) #' @param axis_colour The colour of the grid axes and labels (default="black") #' @param axis_width The width of the axis lines (default=1) #' @param axis_title_size Font size for axis titles (default = 5) #' @param axis_label_size Font size for axis labels (default = 3) #' @param marker_alpha The alpha parameter for markers (default = 0.7) #' @param marker_size Size of the markers (default = 3) #' @param marker_outline_colour Colour for marker outline (default = white) #' @param marker_outline_width Width for marker outline (default = 0.5) #' @param legend_size Size for the legend text (default = 20). #' @param ... Optional parameters passed to \code{\link[volcano3D]{polar_grid}} #' e.g. `r_axis_ticks` or `axis_angle` #' @return Returns a polar 'ggplot' object featuring variables on a tri-axis #' radial graph #' @importFrom ggplot2 theme ggplot labs geom_path geom_path geom_text annotate #' geom_point scale_color_manual aes element_blank coord_fixed geom_segment #' arrow unit element_rect aes_string scale_fill_manual element_text #' @importFrom methods is #' @keywords hplot #' @references #' Lewis, Myles J., et al. (2019). #' \href{https://pubmed.ncbi.nlm.nih.gov/31461658/}{ #' Molecular portraits of early rheumatoid arthritis identify clinical and #' treatment response phenotypes.} #' \emph{Cell reports}, \strong{28}:9 #' @seealso \code{\link{polar_coords}} #' @export #' @examples #' data(example_data) #' syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, #' data = t(syn_example_rld)) #' #' radial_ggplot(polar = syn_polar, label_rows = c("COBL")) radial_ggplot <- function(polar, type = 1, colours = NULL, label_rows = NULL, arrow_length = 1, label_size = 5, colour_code_labels = FALSE, label_colour = "black", grid_colour = "grey80", grid_width = 0.7, axis_colour = "black", axis_width = 1, axis_title_size = 5, axis_label_size = 3, marker_alpha = 0.7, marker_size = 3, marker_outline_colour = "white", marker_outline_width = 0.5, legend_size = 20, ...){ if (is(polar, "polar")) { args <- as.list(match.call())[-1] return(do.call(radial_ggplot_v1, args)) # for back compatibility } if(! is(polar, "volc3d")) stop("polar must be a 'volc3d' object") polar_df <- polar@df[[type]] grid <- polar_grid(r_vector = polar_df$r, ...) grid@polar_grid <- grid@polar_grid[grid@polar_grid$area != "cylinder", ] # markers are plotted in order of rows so push ns to the bottom of plot polar_df <- polar_df[order(polar_df$lab), ] old_levels <- levels(polar_df$lab) polar_df$lab <- droplevels(polar_df$lab) if (is.null(colours)) { colours <- polar@scheme colours <- colours[old_levels %in% levels(polar_df$lab)] } # alignment for text hadj <- -1*sign(grid@axis_labs$x) hadj[hadj == -1] <- 0 polar_df$cg <- polar_df$col if(! is.null(label_rows)){ if(! all(is.numeric(label_rows))) { if(! all(label_rows %in% rownames(polar_df))){ stop("label_rows must be in rownames(polar_df)") }} if(all(is.numeric(label_rows))) { if(! all(label_rows < nrow(polar_df))){ stop("label_rows not in 1:nrow(polar_df)") }} annotation_df <- polar_df[label_rows, ] annotation_df$label <- rownames(annotation_df) annotation_df$theta <- atan(annotation_df$y/annotation_df$x) annotation_df$xend <- arrow_length*sign(annotation_df$x)* abs(grid@r*cos(annotation_df$theta)) annotation_df$yend <- arrow_length*sign(annotation_df$y)* abs(grid@r*sin(annotation_df$theta)) } p <- ggplot(polar_df, aes_string(x = "x", y = "y")) + labs(x = "", y = "", color = "") # Concentric circles and radial spokes rem <- which(is.na(grid@polar_grid$x)) invisible(lapply(1:(length(rem)-1), function(g){ p <<- p + geom_path(data = grid@polar_grid[(rem[g]+1):(rem[g+1]-1), ], aes_string(x = "x", y = "y"), size=grid_width, colour=grid_colour) })) # Three radial axes rem <- c(0, which(is.na(grid@axes$x) )) invisible(lapply(1:(length(rem)-1), function(g){ p <<- p + geom_path(data = grid@axes[(rem[g]+1):(rem[g+1]-1), ], aes_string(x = "x", y = "y"), size=axis_width, color=axis_colour) })) p <- p + # radial axes ticks geom_text(data = grid@text_coords, aes_string(x = "x", y = "y", label = "text"), color = axis_colour, vjust = -1, size = axis_label_size) + # Axes titles (three groups) annotate(geom = "text", x = grid@axis_labs$x, y = grid@axis_labs$y, hjust = hadj, vjust = -1*sign(grid@axis_labs$y), label = levels(polar@outcome), color = axis_colour, size = axis_title_size) + # Add markers geom_point(aes_string(fill = "lab"), size = marker_size, alpha = marker_alpha, color = marker_outline_colour, stroke = marker_outline_width, shape = 21) + scale_fill_manual(name="", values = as.character(colours)) + # Set the background colour etc. theme(axis.line = element_blank(), axis.text.x = element_blank(), axis.ticks = element_blank(), axis.text.y = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.key = element_blank(), legend.justification = c(1, 1), legend.position = "right", legend.text = element_text(size = legend_size), legend.background = element_rect(fill="transparent", colour=NA), plot.background = element_rect(fill="transparent", color=NA), panel.background = element_rect(fill="transparent", colour=NA)) + # Fix the aspect ratio coord_fixed(ratio = 1, xlim = c(-grid@r, grid@r*1.25), ylim = c(-grid@r, grid@r)) # Add any labeling desired if(! is.null(label_rows)){ annotation_df$xend1 <- 0.9*annotation_df$xend annotation_df$yend1 <- 0.9*annotation_df$yend annotation_df$xend2 <- 0.95*annotation_df$xend annotation_df$yend2 <- 0.95*annotation_df$yend annotation_df$xadj <- 0 annotation_df$xadj[annotation_df$xend1 < 0] <- 1 annotation_df$yadj <- 0 annotation_df$yadj[annotation_df$yend1 < 0] <- 1 if(colour_code_labels) ac <- annotation_df$cg else ac <- label_colour p <- p + geom_segment(data = annotation_df, aes_string(x = "x", y = "y", xend = "xend1", yend = "yend1"), colour = ac, size = 0.5, arrow = arrow(length = unit(0, "cm"))) + geom_text(data = annotation_df, aes_string(x = "xend2", y = "yend2", label = "label"), hjust = "outward", vjust = "outward", color = ac, size = label_size) + geom_point(data = annotation_df, aes_string(x = "x", y = "y"), shape = 1, color = "black", size = marker_size) } return(p) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/radial_ggplot.R
#' @importFrom grDevices col2rgb #' @importFrom stats setNames radial_ggplot_v1 <- function(polar, colours = c("green3", "cyan", "blue", "purple", "red", "gold2"), non_sig_colour = "grey60", colour_scale = "discrete", continuous_shift = 1.33, label_rows = NULL, arrow_length = 1, grid = NULL, fc_or_zscore = "zscore", label_size = 5, colour_code_labels = TRUE, label_colour = NULL, grid_colour = "grey80", grid_width = 0.7, axis_colour = "black", axis_width = 1, axis_title_size = 5, axis_label_size = 3, marker_alpha = 0.7, marker_size = 3, marker_outline_colour = "white", marker_outline_width = 0.5, axis_angle = 1/6, legend_size = 20, ...){ if(! inherits(polar, "polar")) stop("polar must be a polar object") polar_df <- polar@polar if(! is.null(colours) & length(colours) != 6){ stop(paste("colours must be a character vector of plotting colours of", "length six. One colour for each significance group")) } if(! is.numeric(continuous_shift)) { stop('continuous_shift must be numeric') } if(! (0 <= continuous_shift & continuous_shift <= 2) ) { stop('continuous_shift must be between 0 and 2') } if(! colour_code_labels & is.null(label_colour)){ stop('If colour_code_labels is false please enter a valid label_colour') } groups <- levels(polar@sampledata[, polar@contrast]) sig_groups <- c( paste0(groups[1], "+"), paste0(groups[1], "+", groups[2], "+"), paste0(groups[2], "+"), paste0(groups[2], "+", groups[3], "+"), paste0(groups[3], "+"), paste0(groups[1], "+", groups[3], "+") ) # If no colours selected dafault to rgb if(is.null(colours)){ colours <- c("green3", "cyan", "blue", "purple", "red", "gold2") } if(is.null(non_sig_colour)){ stop('Please enter a valid non_sig_colour') } # check if hex or can be converted to hex colours <- unlist(lapply(c(colours, non_sig_colour), function(x) { if(! grepl("#", x) & inherits(try(col2rgb(x), silent = TRUE), "try-error")) { stop(paste(x, 'is not a valid colour')) } else if (! grepl("#", x) ) { y <- col2rgb(x)[, 1] x <- rgb(y[1], y[2], y[3], maxColorValue=255) } return(x) })) colours <- setNames(colours, c(sig_groups, polar@non_sig_name)) if(! inherits(polar_df, "data.frame")) { stop("polar_df must be a data frame") } if(! fc_or_zscore %in% c("zscore", "fc")) { stop("fc_or_zscore must be either 'zscore' or 'fc'") } if(! is.numeric(label_size)) stop('label_size must be a numeric') if(! is.numeric(axis_title_size)) stop('axis_title_size must be a numeric') if(! is.numeric(axis_label_size)) stop('axis_label_size must be a numeric') if(! is.numeric(arrow_length)) stop('arrow_length must be a numeric') if(! is.numeric(marker_size)) stop('marker_size must be a numeric') if(! is.numeric(marker_alpha)) stop('marker_alpha must be a numeric') if(! (marker_alpha >= 0 & marker_alpha <= 1)) { stop('marker_alpha must be between 0 and 1') } polar_df$x <- polar_df[, paste0("x_", fc_or_zscore)] polar_df$y <- polar_df[, paste0("y_", fc_or_zscore)] polar_df$r <- polar_df[, paste0("r_", fc_or_zscore)] # Set up the colours - pick the most highly expressed group polar_df$col <- as.character(colours[match(polar_df$sig, names(colours))]) # Calculate the continuous colours offset <- (polar_df$angle[!is.na(polar_df$angle)] + continuous_shift/2) offset[offset > 1] <- offset[offset > 1] - 1 polar_df$hue <- hsv(offset, 1, 1) polar_df$hue[polar_df$sig == polar@non_sig_name] <- non_sig_colour # account for duplicated colours if(any(duplicated(colours))){ warning(paste("Some colours are repeated. These will be compressed", "into one significance group")) colours <- setNames(unique(colours), unlist(lapply(unique(colours), function(x) { paste(names(colours)[colours == x], collapse=" or \n") }))) polar_df$sig <- factor(names(colours)[match(polar_df$col, colours)]) } # make sure the non-sig markers are on the bottom - reshuffle the order polar_df$sig <- factor(polar_df$sig, levels = c(polar@non_sig_name, as.character( unique(polar_df$sig[polar_df$sig != polar@non_sig_name])))) cols <- colours[match(levels(droplevels(polar_df$sig)), names(colours))] if(is.null(grid)) { grid <- polar_grid(r_vector = polar_df$r, r_axis_ticks = NULL, axis_angle = axis_angle, ...) } else { if(inherits(grid, "grid")) stop('grid must be a grid object')} grid@polar_grid <- grid@polar_grid[grid@polar_grid$area != "cylinder", ] # markers are plotted in order of rows so push ns to the bottom of plot polar_df <- polar_df[c(which(polar_df$sig == polar@non_sig_name), which(polar_df$sig != polar@non_sig_name)), ] # alignment for text hadj <- -1*sign(grid@axis_labs$x) hadj[hadj == -1] <- 0 polar_df$cg <- switch(colour_scale, "discrete"=polar_df$col, "continuous"=polar_df$hue) if(! is.null(label_rows)){ if(! all(is.numeric(label_rows))) { if(! all(label_rows %in% rownames(polar_df))){ stop("label_rows must be in rownames(polar_df)") }} if(all(is.numeric(label_rows))) { if(! all(label_rows < nrow(polar_df))){ stop("label_rows not in 1:nrow(polar_df)") }} annotation_df <- polar_df[label_rows, ] annotation_df$theta <- atan(annotation_df$y/annotation_df$x) annotation_df$xend <- arrow_length*sign(annotation_df$x)* abs(grid@r*cos(annotation_df$theta)) annotation_df$yend <- arrow_length*sign(annotation_df$y)* abs(grid@r*sin(annotation_df$theta)) } p <- ggplot(polar_df, aes_string(x = "x", y = "y")) + labs(x = "", y = "", color = "") # Concentric circles and radial spokes rem <- which(is.na(grid@polar_grid$x)) invisible(lapply(1:(length(rem)-1), function(g){ p <<- p + geom_path(data = grid@polar_grid[(rem[g]+1):(rem[g+1]-1), ], aes_string(x = "x", y = "y"), size=grid_width, colour=grid_colour) })) # Three radial axes rem <- c(0, which(is.na(grid@axes$x) )) invisible(lapply(1:(length(rem)-1), function(g){ p <<- p + geom_path(data = grid@axes[(rem[g]+1):(rem[g+1]-1), ], aes_string(x = "x", y = "y"), size=axis_width, color=axis_colour) })) p <- p + # radial axes ticks geom_text(data = grid@text_coords, aes_string(x = "x", y = "y", label = "text"), color = axis_colour, vjust = -1, size = axis_label_size) + # Axes titles (three groups) annotate(geom = "text", x = grid@axis_labs$x, y = grid@axis_labs$y, hjust = hadj, vjust = -1*sign(grid@axis_labs$y), label = levels(polar@sampledata[, polar@contrast]), color = axis_colour, size = axis_title_size) + # Add markers geom_point(aes_string(fill=switch(colour_scale, "discrete"= "sig", "continuous" = "hue")), size = marker_size, alpha = marker_alpha, color = marker_outline_colour, stroke = marker_outline_width, shape = 21) + scale_fill_manual(name="", values = switch(colour_scale, "discrete" = as.character(cols), "continuous" = levels(factor(polar_df$hue)))) + # Set the background colour etc. theme(axis.line = element_blank(), axis.text.x = element_blank(), axis.ticks = element_blank(), axis.text.y = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), legend.key = element_blank(), legend.justification = c(1, 1), legend.position = switch(colour_scale, "discrete"="right", "continuous"="none"), legend.text = element_text(size = legend_size), legend.background = element_rect(fill="transparent", colour=NA), plot.background = element_rect(fill="transparent", color=NA), panel.background = element_rect(fill="transparent", colour=NA)) + # Fix the aspect ratio coord_fixed(ratio = 1, xlim = c(-grid@r, grid@r*1.25), ylim = c(-grid@r, grid@r)) # Add any labeling desired if(! is.null(label_rows)){ annotation_df$xend1 <- 0.9*annotation_df$xend annotation_df$yend1 <- 0.9*annotation_df$yend annotation_df$xend2 <- 0.95*annotation_df$xend annotation_df$yend2 <- 0.95*annotation_df$yend annotation_df$xadj <- 0 annotation_df$xadj[annotation_df$xend1 < 0] <- 1 annotation_df$yadj <- 0 annotation_df$yadj[annotation_df$yend1 < 0] <- 1 if(colour_code_labels) ac <- annotation_df$cg else ac <- label_colour p <- p + geom_segment(data = annotation_df, aes_string(x = "x", y = "y", xend = "xend1", yend = "yend1"), colour = ac, size = 0.5, arrow = arrow(length = unit(0, "cm"))) + geom_text(data = annotation_df, aes_string(x = "xend2", y = "yend2", label = "label"), hjust = "outward", vjust = "outward", color = ac, size = label_size) + geom_point(data = annotation_df, aes_string(x = "x", y = "y"), shape = 1, color = "black", size = marker_size) } return(p) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/radial_ggplot_old.R
#' Three-way radial comparison Polar Plot (using plotly) #' #' This function creates an interactive plotly object which maps differential #' expression onto a polar coordinates. #' #' @param polar A 'volc3d' object with the p-values between groups of interest #' and polar coordinates created by \code{\link{polar_coords}}, #' \code{\link{deseq_polar}} or \code{\link{voom_polar}}. #' @param type Numeric value whether to use scaled (Z-score) or unscaled (fold #' change) as magnitude. Options are 1 = Z-score (default) or 2 = #' unscaled/fold change. #' @param colours A vector of colour names or hex triplets for the #' non-significant points and each of the six groups. #' @param label_rows A vector of row names or numbers to label. #' @param arrow_length The length of label arrows (default = 80). #' @param label_size Font size of labels/annotations (default = 14) #' @param colour_code_labels Logical whether label annotations should be colour #' coded. If FALSE label_colour is used. #' @param label_colour HTML colour of annotation labels if not colour coded. #' @param grid_colour The colour of the grid (default="grey80") #' @param grid_width The width of the grid lines (default=1) #' @param marker_size Size of the markers (default = 6) #' @param marker_alpha Opacity for the markers (default = 0.7) #' @param marker_outline_colour Colour for marker outline (default = white) #' @param marker_outline_width Width for marker outline (default = 0.5) #' @param axis_title_size Font size for axis titles (default = 16) #' @param axis_label_size Font size for axis labels (default = 10) #' @param axis_colour The colour of the grid axes and labels (default="black") #' @param axis_width The width of the axis lines (default=2) #' @param ... Optional parameters passed to \code{\link[volcano3D]{polar_grid}} #' e.g. `r_axis_ticks` or `axis_angle` #' @return Returns a plotly plot featuring variables on a tri-axis radial graph #' @details #' This function builds a layered plotly object. By default this produces an SVG #' output, but this can be slow with 1000s of points. For large number of points #' we recommend switching to webGL by piping to `toWebGL()` as shown in the #' examples. #' #' @seealso \code{\link{polar_coords}} #' @importFrom plotly plot_ly add_trace add_text add_markers layout #' @importFrom magrittr %>% #' @importFrom methods is #' @references #' Lewis, Myles J., et al. (2019). #' \href{https://pubmed.ncbi.nlm.nih.gov/31461658/}{ #' Molecular portraits of early rheumatoid arthritis identify clinical and #' treatment response phenotypes.} #' \emph{Cell reports}, \strong{28}:9 #' @keywords hplot iplot #' @export #' @examples #' data(example_data) #' syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, #' data = t(syn_example_rld)) #' #' radial_plotly(polar = syn_polar, label_rows = c("COBL")) #' #' ## Faster webGL version for large numbers of points #' library(plotly) #' radial_plotly(polar = syn_polar, label_rows = c("COBL")) %>% #' toWebGL() #' radial_plotly <- function(polar, type = 1, colours = polar@scheme, label_rows = NULL, arrow_length = 80, label_size = 14, colour_code_labels = FALSE, label_colour = "black", grid_colour = "grey80", grid_width = 1, marker_size = 7, marker_alpha = 0.8, marker_outline_colour = "white", marker_outline_width = 0.5, axis_title_size = 16, axis_label_size = 10, axis_colour = "black", axis_width = 2, ...){ if (is(polar, "polar")) { args <- as.list(match.call())[-1] return(do.call(radial_plotly_v1, args)) # for back compatibility } if(! is(polar, "volc3d")) stop("Not a 'volc3d' class object") df <- polar@df[[type]] grid <- polar_grid(df$r, df$z, ...) grid@polar_grid <- grid@polar_grid[grid@polar_grid$area != "cylinder", ] polar_grid <- grid@polar_grid axes <- grid@axes axis_labs <- grid@axis_labs r <- grid@r text_coords <- grid@text_coords # Annotate gene labels if (length(label_rows) != 0) { if(! all(is.numeric(label_rows))) { if(! all(label_rows %in% rownames(df))) { stop("label_rows must be in rownames(df)") }} if(all(is.numeric(label_rows))) { if(! all(label_rows < nrow(df))) { stop("label_rows not in 1:nrow(df)") }} annot <- lapply(label_rows, function(i) { row <- df[i, ] theta <- atan(row$y/row$x) if(colour_code_labels) ac <- row$col else ac <- label_colour list(x = row$x, y = row$y, text = rownames(row), textangle = 0, ax = sign(row$x)*arrow_length*cos(theta), ay = -sign(row$x)*arrow_length*sin(theta), font = list(color = ac, size = label_size), arrowcolor = ac, arrowwidth = 1, arrowhead = 0, xanchor = "auto", yanchor = "auto", arrowsize = 1.5) }) } else {annot <- list()} # plotly plot # add the grid p <- plot_ly(data = df, x = ~x, mode = "none", type = "scatter", colors = colours, showlegend = FALSE) %>% add_trace(x = polar_grid$x, y = polar_grid$y, color = I(grid_colour), line = list(width = grid_width), showlegend = FALSE, type = "scatter", mode = "lines", hoverinfo = "none") %>% # add the "horizontal" axes add_trace(x = axes$x, y = axes$y, color = I(axis_colour), line = list(width = axis_width), showlegend = FALSE, type = "scatter", mode = "lines", hoverinfo = "none", inherit = FALSE) %>% # add the label text add_text(x = axis_labs$x, y = axis_labs$y, text = levels(polar@outcome), color = I(axis_colour), type = "scatter", mode = "text", textfont = list(size = axis_title_size), textposition = axis_labs$adjust, hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% # label radial axis add_text(x = text_coords$x, y = -text_coords$y, text = text_coords$text, textposition = 'top center', textfont = list(size = axis_label_size), color = I(axis_colour), hoverinfo = 'none', type = "scatter", showlegend = FALSE, inherit = FALSE) %>% layout(showlegend = TRUE, xaxis = list(title = "", range = c(-r*1.02, r*1.4), zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE, scaleratio = 1, scaleanchor = "y", autoscale = TRUE), yaxis = list(title = "", range = c(-r, r), zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE), plot_bgcolor = "rgba(0,0,0,0)", paper_bgcolor = 'rgba(0,0,0,0)', autosize = TRUE, uirevision=list(editable=TRUE), annotations = annot) %>% # add the markers add_markers(data = df, x = ~x, y = ~y, text = rownames(df), opacity = marker_alpha, color = ~lab, colors = colours, marker = list(size = marker_size, line = list(color = marker_outline_colour, width = marker_outline_width)), hoverinfo = 'text', key = rownames(df), inherit = FALSE, type = "scatter", mode = "markers") return(p) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/radial_plotly.R
#' @importFrom grDevices col2rgb #' @importFrom stats setNames radial_plotly_v1 <- function(polar, colours = c("green3", "cyan", "blue", "purple", "red", "gold2"), non_sig_colour = "grey60", colour_scale = "discrete", continuous_shift = 1.33, label_rows = NULL, arrow_length = 50, grid = NULL, fc_or_zscore = "zscore", label_size = 14, colour_code_labels = TRUE, label_colour = NULL, hover_text = "label", grid_colour = "grey80", grid_width = 1, marker_size = 6, marker_alpha = 0.7, marker_outline_colour = "white", marker_outline_width = 0.5, axis_title_size = 16, axis_label_size = 10, axis_colour = "black", axis_width = 2, axis_ticks = NULL, axis_angle = 5/6, plot_height = 700, plot_width = 700, source = "radial", ...){ if(! is(polar, "polar")) stop("polar must be a polar object") polar_df <- cbind(polar@polar, polar@pvalues) polar_df$hover <- eval(parse( text = paste0("with(polar_df, ", hover_text, ")"))) polar_df <- polar_df[, c(colnames(polar@polar), "hover")] if(! is.null(colours) & length(colours) != 6){ stop(paste("colours must be a character vector of plotting colours of", "length six. One colour for each significance group")) } groups <- levels(polar@sampledata[, polar@contrast]) sig_groups <- c( paste0(groups[1], "+"), paste0(groups[1], "+", groups[2], "+"), paste0(groups[2], "+"), paste0(groups[2], "+", groups[3], "+"), paste0(groups[3], "+"), paste0(groups[1], "+", groups[3], "+") ) # If no colours selected dafault to rgb if(is.null(colours)){ colours <- c("green3", "cyan", "blue", "purple", "red", "gold2") } if(is.null(non_sig_colour)){ stop('Please enter a valid non_sig_colour') } if(! colour_code_labels & is.null(label_colour)){ stop('If colour_code_labels is false please enter a valid label_colour') } # check if hex or can be converted to hex colours <- unlist(lapply(c(non_sig_colour, colours), function(x) { if(! grepl("#", x) & inherits(try(col2rgb(x), silent = TRUE), "try-error")) { stop(paste(x, 'is not a valid colour')) } else if (! grepl("#", x) ) { y <- col2rgb(x)[, 1] x <- rgb(y[1], y[2], y[3], maxColorValue=255) } return(x) })) colours <- setNames(colours, c(polar@non_sig_name, sig_groups)) if(! inherits(polar_df, "data.frame")) { stop("polar_df must be a data frame") } if(! fc_or_zscore %in% c("zscore", "fc")) { stop("fc_or_zscore must be either 'zscore' or 'fc'") } if(! is.numeric(label_size)) stop('label_size must be a numeric') if(! is.numeric(axis_title_size)) stop('axis_title_size must be a numeric') if(! is.numeric(axis_label_size)) stop('axis_label_size must be a numeric') if(! is.numeric(arrow_length)) stop('arrow_length must be a numeric') polar_df$x <- polar_df[, paste0("x_", fc_or_zscore)] polar_df$y <- polar_df[, paste0("y_", fc_or_zscore)] polar_df$r <- polar_df[, paste0("r_", fc_or_zscore)] polar_df <- polar_df[! is.nan(polar_df$x), ] if(is.null(grid)) { grid <- polar_grid(r_vector = polar_df$r, r_axis_ticks = NULL, axis_angle = axis_angle, ...) } else{ if(inherits(grid, "grid")) stop('grid must be a grid object') } if(! is.numeric(continuous_shift)) { stop('continuous_shift must be numeric') } if(! (0 <= continuous_shift & continuous_shift <= 2) ) { stop('continuous_shift must be between 0 and 2') } grid@polar_grid <- grid@polar_grid[grid@polar_grid$area != "cylinder", ] polar_grid <- grid@polar_grid axes <- grid@axes axis_labs <- grid@axis_labs r <- grid@r text_coords <- grid@text_coords # Set up the colours - pick the most highly expressed group polar_df$col <- as.character(colours[match(polar_df$sig, names(colours))]) # Calculate the continuous colours offset <- (polar_df$angle[!is.na(polar_df$angle)] + continuous_shift/2) offset[offset > 1] <- offset[offset > 1] - 1 polar_df$hue <- hsv(offset, 1, 1) polar_df$hue[polar_df$sig == polar@non_sig_name] <- non_sig_colour if(any(duplicated(colours))){ warning(paste("Some colours are repeated. These will be compressed", "into one significance group")) colours <- setNames( unique(colours), unlist(lapply(unique(colours), function(x) { groups_involved <- names(colours)[colours == x] # Filter onto those included only, unless empty if(any(groups_involved %in% polar_df$sig)){ groups_involved <- groups_involved[groups_involved %in% polar_df$sig] } sub(",\\s+([^,]+)$", " or\n\\1", paste(groups_involved, collapse=", /n")) }))) polar_df$sig <- factor(names(colours)[match(polar_df$col, colours)]) } colour_levels <- colours colour_levels <- colour_levels[names(colour_levels) %in% c(levels(polar_df$sig), polar@non_sig_name)] # Align the levels polar_df$sig <- factor(polar_df$sig, levels=names(colour_levels)) # Annotate gene labels if (length(label_rows) != 0) { if(! all(is.numeric(label_rows))) { if(! all(label_rows %in% rownames(polar_df))) { stop("label_rows must be in rownames(polar_df)") }} if(all(is.numeric(label_rows))) { if(! all(label_rows < nrow(polar_df))) { stop("label_rows not in 1:nrow(polar_df)") }} annot <- lapply(label_rows, function(i) { row <- polar_df[i, ] theta <- atan(row$y/row$x) if(colour_code_labels) ac <- row$col else ac <- label_colour list(x = row$x, y = row$y, text = as.character(row$label), textangle = 0, ax = sign(row$x)*arrow_length*grid@r*cos(theta), ay = -1*sign(row$x)*arrow_length*grid@r*sin(theta), font = list(color = ac, size = label_size), arrowcolor = ac, arrowwidth = 1, arrowhead = 0, xanchor = ifelse(row$x < 0, "right", "left"), xanchor = ifelse(row$y < 0, "bottom", "top"), arrowsize = 1.5) }) } else {annot <- list()} polar_df <- polar_df[c(which(polar_df$hue == non_sig_colour), which(polar_df$hue != non_sig_colour)), ] # plotly plot p <- plot_ly(data = polar_df, x = ~x, mode = "none", type = "scatter", colors = switch(colour_scale, "discrete" = colour_levels, "continuous" = NULL), source = source, showlegend = FALSE) %>% # add the grid add_trace(x = polar_grid$x, y = polar_grid$y, color = I(grid_colour), line = list(width = grid_width), showlegend = FALSE, type = "scatter", mode = "lines", hoverinfo = "none") %>% # add the "horizontal" axes add_trace(x = axes$x, y = axes$y, color = I(axis_colour), line = list(width = axis_width), showlegend = FALSE, type = "scatter", mode = "lines", hoverinfo = "none", inherit = FALSE) %>% # add the label text add_text(x = axis_labs$x, y = axis_labs$y, text = levels(polar@sampledata[, polar@contrast]), color = I(axis_colour), type = "scatter", mode = "text", textfont = list(size = axis_title_size), textposition = axis_labs$adjust, hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% layout(showlegend = TRUE, xaxis = list(title = "", range = c(-grid@r, NULL), zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE, scaleratio = 1, scaleanchor = "y", autoscale = TRUE), yaxis = list(title = "", range = c(-grid@r, grid@r), zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE), plot_bgcolor = "rgba(0,0,0,0)", paper_bgcolor = 'rgba(0,0,0,0)', autosize = TRUE, uirevision=list(editable=TRUE), annotations = annot) %>% # label radial axis add_text(x = text_coords$x, y = -text_coords$y, text = text_coords$text, textposition = 'top center', textfont = list(size = axis_label_size), color = I(axis_colour), hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% # add the markers add_markers(data = polar_df, x = ~x, y = ~y, key = ~label, text = ~hover, opacity = marker_alpha, color = ~switch(colour_scale, "discrete" = sig, "continuous" = I(hue)), colors = switch(colour_scale, "discrete" = levels(polar_df$col), "continuous" = NULL), marker = list(size = marker_size, sizemode = 'diameter', line = list(color = marker_outline_colour, width = marker_outline_width)), hoverinfo = 'text', key = rownames(polar_df), inherit = TRUE, type = "scatter", mode = "markers", text = rownames(polar_df), showlegend = (colour_scale == "discrete")) return(p) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/radial_plotly_old.R
#' Plots grid objects for inspection using plotly #' #' This function creates an interactive grids in polar and cylindrical #' coordinates #' @param grid A grid object produced by \code{\link{polar_grid}}. #' @param plot_height The plot height in px (default=700), #' @param axis_angle The angle in radians at which to add axis (default=0). #' @param z_axis_title_offset Offset for z axis title (default=1.2). #' @return Returns a list containing a polar and cylindrical coordinate system. #' @importFrom plotly plot_ly add_trace add_text layout %>% #' @references #' Lewis, Myles J., et al. (2019). #' \href{https://pubmed.ncbi.nlm.nih.gov/31461658/}{ #' Molecular portraits of early rheumatoid arthritis identify clinical and #' treatment response phenotypes.} #' \emph{Cell reports}, \strong{28}:9 #' @keywords hplot iplot #' @export #' @examples #' data(example_data) #' syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, #' data = t(syn_example_rld)) #' #' grid <- polar_grid(r_vector=syn_polar@df[[1]]$r, #' z_vector=syn_polar@df[[1]]$z, #' r_axis_ticks = NULL, #' z_axis_ticks = NULL) #' p <- show_grid(grid) #' p$polar #' p$cyl show_grid <- function(grid, plot_height=700, axis_angle=0, z_axis_title_offset=1.2){ if(! is.numeric(axis_angle)) { stop('axis_angle must be a numeric') } if(! is.numeric(plot_height)) { stop('plot_height must be a numeric') } if(class(grid)[1] != "grid") { stop('grid must be a grid object created by polar_grid()') } axis_settings <- list(title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE, autotick = FALSE) axis_settings_xy <- list(title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE, autotick = FALSE, showspikes = FALSE) axis_settings_xy[['range']] <- c(-grid@r, grid@r)*1.05*z_axis_title_offset grid_cyl <- grid cyl <- plot_ly(height = plot_height) %>% add_trace(x = grid_cyl@polar_grid$x, y = grid_cyl@polar_grid$y, z = grid_cyl@polar_grid$z, color = I("#CBCBCB"), line = list(width = 2), showlegend = FALSE, type = "scatter3d", mode = "lines", hoverinfo = "none", inherit = FALSE) %>% # Horizontal axes add_trace(x = grid_cyl@axes$x, y = grid_cyl@axes$y, z = 0, color = I("black"), line = list(width = 2), showlegend = FALSE, type = "scatter3d", mode = "lines", hoverinfo = "none", inherit = FALSE) %>% # Axis labels add_text(x = grid_cyl@axis_labs$x *1.1, y = grid_cyl@axis_labs$y *1.1, z = 0, text = c("A", "B", "C"), color = I("black"), type = "scatter3d", mode = "text", textfont = list(size = 16), textposition = 'middle center', hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% # label z axis add_text(x = c(rep(1.05*grid_cyl@r*sinpi(axis_angle), grid_cyl@n_z_breaks), z_axis_title_offset*grid_cyl@r*sinpi(axis_angle)), y = c(rep(1.05*grid_cyl@r*cospi(axis_angle), grid_cyl@n_z_breaks), z_axis_title_offset*grid_cyl@r*cospi(axis_angle)), z = c(grid_cyl@z_breaks, grid_cyl@z/2)*0.95, text = c(grid_cyl@z_breaks, '-log<sub>10</sub>P'), textposition = 'middle left', textfont = list(size = 10), color = I("black"), hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% add_trace(x = grid_cyl@r*sinpi(axis_angle), y = grid_cyl@r*cospi(axis_angle), z = c(0, grid_cyl@z), color = I("black"), line = list(width = 2), showlegend = FALSE, type = "scatter3d", mode = "lines", hoverinfo = "none", inherit = FALSE) %>% # label radial axis add_text(x = grid_cyl@text_coords$x, y = grid_cyl@text_coords$y, z = grid_cyl@z * 0.03, text = grid_cyl@text_coords$text, textposition = 'middle center', textfont = list(size = 10), color = I("black"), hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% layout(showlegend = TRUE, dragmode = "turntable", margin = list(0, 0, 0, 0), paper_bgcolor = 'rgba(0, 0, 0, 0)', plot_bgcolor = 'rgba(0, 0, 0, 0)', scene = list(xaxis = axis_settings_xy, yaxis = axis_settings_xy, zaxis = axis_settings, aspectratio = list(x = 1, y = 1, z = 0.8))) grid_polar <- grid grid_polar@polar_grid <- grid_polar@polar_grid[grid_polar@polar_grid$area != "cylinder", ] polar <- plot_ly(height = plot_height) %>% # add the grid add_trace(x = grid_polar@polar_grid$x, y = grid_polar@polar_grid$y, color = I("#CBCBCB"), line = list(width = 1), showlegend = FALSE, type = "scatter", mode = "lines", hoverinfo = "none") %>% # add the "horizontal" axes add_trace(x = grid_polar@axes$x, y = grid_polar@axes$y, color = I("black"), line = list(width = 2), showlegend = FALSE, type = "scatter", mode = "lines", hoverinfo = "none", inherit = FALSE) %>% # add the label text add_text(x = grid_polar@axis_labs$x, y = grid_polar@axis_labs$y, text = c("A", "B", "C"), color = I("black"), type = "scatter", mode = "text", textfont = list(size = 16), textposition = grid_polar@axis_labs$adjust, hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% # label radial axis add_text(x = grid_polar@text_coords$x, y = -grid_polar@text_coords$y, text = grid_polar@text_coords$text, textposition = 'top center', textfont = list(size = 10), color = I("black"), hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% layout(showlegend = TRUE, xaxis = list(title = "", range = c(-grid_polar@r, grid_polar@r), zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE, scaleratio = 1, scaleanchor = "y", autoscale = TRUE), yaxis = list(title = "", range = c(-grid_polar@r, grid_polar@r), zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE), plot_bgcolor = "rgba(0,0,0,0)", paper_bgcolor = 'rgba(0,0,0,0)', autosize = TRUE) return(list("polar"=polar, "cylindrical"=cyl)) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/show_grid.R
#' Extract a subset population #' #' Subsets data according to the significance groups. #' @param polar A polar object including expression data from groups of #' interest. Created by \code{\link{polar_coords}}. #' @param significance Which significance factors to subset to. If `NULL` #' all levels except 'ns' (non-significant) are selected. #' @param output What object to return. Options are "pvals", "padj", "data", #' "df" for subset dataframes, or "polar" to subset the entire 'volc3d' class #' object. #' @references #' Lewis, Myles J., et al. (2019). #' \href{https://pubmed.ncbi.nlm.nih.gov/31461658/}{ #' Molecular portraits of early rheumatoid arthritis identify clinical and #' treatment response phenotypes.} #' \emph{Cell reports}, \strong{28}:9 #' @importFrom methods slot #' @return Returns an object (type defined by `output`) with rows susbet to #' those which satisfy the significance condition. #' @export #' @examples #' data(example_data) #' syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, #' data = t(syn_example_rld)) #' #' subset <- significance_subset(syn_polar, "L+", "df") significance_subset <- function(polar, significance = NULL, output = "pvals"){ if(is.null(significance)) significance <- levels(polar@df[[1]]$lab)[-1] if(! all(significance %in% levels(polar@df[[1]]$lab))){ stop("`significance` must be in levels(polar@df[[1]]$lab)") } if(!is(polar, "volc3d")) stop("polar must be a 'volc3d' class object") if(! output %in% c("pvals", "padj", "data", "df", "polar")){ stop("`output` must be one of 'pvals', 'padj', 'data', 'df', 'polar'") } rows <- polar@df[[1]]$lab %in% significance polar@pvals <- polar@pvals[rows, ] polar@padj <- polar@padj[rows, ] polar@data <- polar@data[, rows] polar@df[[1]] <- polar@df[[1]][rows, ] polar@df[[2]] <- polar@df[[2]][rows, ] if(output == "polar"){ return(polar) } else { return(slot(polar, output)) } }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/significance_subset.R
#' Three-Dimensional Volcano Plot #' #' Plots the three-way comparisons of variables such as gene expression data in #' 3D space using plotly. x, y position represents polar position on 3 axes #' representing the amount each variable or gene tends to each of the 3 #' categories. The z axis represents -log10 P value for the one-way test #' comparing each variable across the 3 groups. #' #' @param polar Object of S4 class 'volc3d' following call to either #' \code{\link{polar_coords}}, \code{\link{deseq_polar}} or #' \code{\link{voom_polar}} #' @param type Either `1` or `2` specifying type of polar coordinates: `1` = #' Z-scaled, `2` = unscaled (equivalent to log2 fold change for gene #' expression). #' @param label_rows A vector of row names or numbers to label #' @param arrow_length The length of label arrows (default 100) #' @param label_size font size for labels (default 14). #' @param colour_code_labels Logical whether label annotations should be colour #' coded. If `FALSE` `label_colour` is used. #' @param label_colour HTML colour of annotation labels if not colour coded. #' @param grid_colour The colour of the cylindrical grid (default "grey80") #' @param grid_width The width of the grid lines (default 2) #' @param grid_options Optional list of additional arguments to pass to #' \code{\link{polar_grid}}, eg. `z_axis_ticks` and `r_axis_ticks` #' @param axis_colour The colour of the grid axes and labels (default "black") #' @param axis_width The width of axis lines (default 2) #' @param marker_size Size of the markers (default 3) #' @param marker_outline_width Width for marker outline (default 0 means no #' outline) #' @param marker_outline_colour Colour for marker outline (default white) #' @param z_axis_title_offset The position scaling between grid and z axis title #' (default=1.2) #' @param z_axis_title_size The font size for the z axis title (default=12) #' @param z_axis_angle Angle in radians for the position of z axis (default #' 0.5) #' @param radial_axis_title_size The font size for the radial (default=15) #' @param radial_axis_title_offset The position scaling between grid and radial #' axis title (default=1.2) #' @param xy_aspectratio The aspect ratio for the xy axis compared to z (default #' 1). Increasing this makes the grid wider in the plot window. #' @param z_aspectratio The aspect ratio for the z axis compared to x and y #' (default 0.8). Decreasing this makes the plot appear more squat. #' @param camera_eye The (x,y,z) components of the start 'eye' camera vector. #' This vector determines the view point about the origin of this scene. #' @param ... Optional arguments passed to \code{\link[plotly:plot_ly]{plot_ly}} #' @return Returns a cylindrical 3D plotly plot featuring variables on a #' tri-axis radial graph with the -log10(multi-group test p-value) on the #' z-axis #' @references #' Lewis, Myles J., et al. (2019). #' \href{https://pubmed.ncbi.nlm.nih.gov/31461658/}{ #' Molecular portraits of early rheumatoid arthritis identify clinical and #' treatment response phenotypes.} #' \emph{Cell reports}, \strong{28}:9 #' @seealso \code{\link{polar_coords}} #' #' @examples #' data(example_data) #' syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, #' data = t(syn_example_rld)) #' volcano3D(syn_polar) #' #' @importFrom plotly plot_ly add_trace add_text layout #' @importFrom magrittr %>% #' @importFrom methods is #' @export #' volcano3D <- function(polar, type = 1, label_rows = c(), label_size = 14, arrow_length = 100, colour_code_labels = FALSE, label_colour = "black", grid_colour = "grey80", grid_width = 2, grid_options = NULL, axis_colour = "black", axis_width = 2, marker_size = 3, marker_outline_width = 0, marker_outline_colour = "white", z_axis_title_offset = 1.2, z_axis_title_size = 12, z_axis_angle = 0.5, radial_axis_title_size = 14, radial_axis_title_offset = 1.2, xy_aspectratio = 1, z_aspectratio = 0.8, camera_eye = list(x=0.9, y=0.9, z=0.9), ...) { # Check the input data if (is(polar, "polar")) { args <- as.list(match.call())[-1] return(do.call(volcano3D_v1, args)) # for back compatibility } if (!is(polar, "volc3d")) stop("Not a 'volc3d' class object") args <- list(r_vector = polar@df[[type]]$r, z_vector = polar@df[[type]]$z) args <- append(args, grid_options) # Build the coordinate system grid <- do.call(polar_grid, args) polar_grid <- grid@polar_grid axes <- grid@axes axis_labels <- grid@axis_labs h <- grid@z R <- grid@r max_offset <- max(c(z_axis_title_offset, radial_axis_title_offset)) xyrange <- c(-1.05*(max_offset)*R, 1.05*max_offset*R) axis_settings <- list(title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE, autotick = FALSE, showspikes = FALSE) axis_settings_xy <- list(title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE, autotick = FALSE, showspikes = FALSE, range = xyrange) df <- polar@df[[type]] # Label rows if(length(label_rows) != 0){ if(! all(is.numeric(label_rows))) { if(! all(label_rows %in% rownames(df))) { stop("label_rows must be in rownames(polar_df)") }} if(all(is.numeric(label_rows))) { if(! all(label_rows < nrow(df))) { stop("label_rows not in 1:nrow(polar_df)") }} annot <- lapply(label_rows, function(i) { row <- df[i, ] if(colour_code_labels) ac <- row$col else ac <- label_colour annot <- list(x = row$x, y = row$y, z = row$z, text = rownames(row), textangle = 0, ax = arrow_length, ay = 0, arrowcolor = ac, font = list(color = ac), arrowwidth = 1, arrowhead = 0, arrowsize = 1.5, yanchor = "middle") }) } else {annot <- list()} # Generate plotly plot plot_ly(polar@df[[type]], x = ~x, y = ~y, z = ~z, color = ~lab, colors = polar@scheme, hoverinfo='text', text = ~paste0(rownames(polar@df[[type]]), "<br>theta = ", as.integer(angle), ", r = ", formatC(r, digits = 3), "<br>P = ", format(pvalue, digits = 3, scientific = 3)), key = rownames(polar@df[[type]]), marker = list(size = marker_size, line = list(color = marker_outline_colour, width = marker_outline_width)), type = "scatter3d", mode = "markers", ...) %>% # Add the cylindrical grid add_trace(x = polar_grid$x, y = polar_grid$y, z = polar_grid$z, color = I(grid_colour), line = list(width = grid_width), showlegend = FALSE, type = "scatter3d", mode = "lines", hoverinfo = "none", inherit = FALSE) %>% # Axes add_trace(x = axes$x, y = axes$y, z = axes$z, color = I(axis_colour), line = list(width = axis_width), showlegend = FALSE, type = "scatter3d", mode = "lines", hoverinfo = "none", inherit = FALSE) %>% add_text( x = radial_axis_title_offset*axis_labels$x, y = radial_axis_title_offset*axis_labels$y, z = 0, text = levels(polar@outcome), color = I(axis_colour), type = "scatter3d", mode = "text", textfont = list(size = radial_axis_title_size), textposition = 'middle center', hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% # label z axis add_text(x = c(rep(R*sinpi(z_axis_angle), grid@n_z_breaks), R*z_axis_title_offset*sinpi(z_axis_angle)), y = c(rep(R*cospi(z_axis_angle), grid@n_z_breaks), R*z_axis_title_offset*cospi(z_axis_angle)), z = c(grid@z_breaks, h/2), text = c(grid@z_breaks, '-log<sub>10</sub>P'), textposition = 'middle left', textfont = list(size = z_axis_title_size), color = I(axis_colour), hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% # label radial axis add_text(x = grid@text_coords$x, y = grid@text_coords$y, z = h * 0.03, text = grid@text_coords$text, textposition = 'middle center', textfont = list(size = 10), color = I(axis_colour), hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% layout( margin = list(0, 0, 0, 0), paper_bgcolor = 'rgba(0, 0, 0, 0)', plot_bgcolor = 'rgba(0, 0, 0, 0)', scene = list( camera = list(eye = camera_eye), aspectratio = list(x = xy_aspectratio, y = xy_aspectratio, z = z_aspectratio), dragmode = "turntable", xaxis = axis_settings_xy, yaxis = axis_settings_xy, zaxis = axis_settings, annotations = annot ), xaxis = list(title = "x"), yaxis = list(title = "y") ) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/volcano3D.R
setClassUnion("character_or_NULL", c("character", "NULL")) setClassUnion("df_or_matrix", c("data.frame", "matrix")) # old S4 class setClass("polar", slots = list(sampledata = "data.frame", contrast = "character", pvalues = "data.frame", multi_group_test = "character_or_NULL", expression = "df_or_matrix", polar = "df_or_matrix", non_sig_name = "character")) #' @importFrom stats setNames volcano3D_v1 <- function(polar, colours=c("green3", "cyan", "blue", "purple", "red", "gold2"), non_sig_colour = "grey60", colour_scale = "discrete", continuous_shift = 1.33, z_axis_title_offset = 1.2, radial_axis_title_offset = 1, z_axis_title_size = 15, radial_axis_title_size = 15, continue_radial_axes = TRUE, axis_width = 2, grid_width = 2, label_rows = c(), grid = NULL, fc_or_zscore = "zscore", label_size = 14, arrow_length=50, colour_code_labels = TRUE, label_colour = NULL, hover_text = "label", grid_colour = "grey80", axis_colour = "black", marker_size = 2.7, marker_alpha = 1, marker_outline_colour = "white", marker_outline_width = 0, axis_angle = 0.5, z_aspectratio = 1, xy_aspectratio = 1, plot_height = 700, camera_eye = list(x=1.25, y=1.25, z=1.25), source="volcano3D", ...){ if(! is(polar, "polar")) stop("polar must be a polar object") polar_df <- cbind(polar@polar, polar@pvalues) polar_df$hover <- eval(parse( text = paste0("with(polar_df, ", hover_text, ")"))) polar_df <- polar_df[, c(colnames(polar@polar), "hover")] if(! colour_code_labels & is.null(label_colour)){ stop('If colour_code_labels is false please enter a valid label_colour') } if(! is.null(colours) & length(colours) != 6){ stop(paste("colours must be a character vector of plotting colours of", "length six. One colour for each significance group")) } groups <- levels(polar@sampledata[, polar@contrast]) sig_groups <- c( paste0(groups[1], "+"), paste0(groups[1], "+", groups[2], "+"), paste0(groups[2], "+"), paste0(groups[2], "+", groups[3], "+"), paste0(groups[3], "+"), paste0(groups[1], "+", groups[3], "+") ) # If no colours selected dafault to rgb if(is.null(colours)){ colours <- c("green3", "cyan", "blue", "purple", "red", "gold2") } if(is.null(non_sig_colour)){ stop('Please enter a valid non_sig_colour') } # check if hex or can be converted to hex colours <- unlist(lapply(c(non_sig_colour, colours), function(x) { if(! grepl("#", x) & inherits(try(col2rgb(x), silent = TRUE), "try-error")) { stop(paste(x, 'is not a valid colour')) } else if (! grepl("#", x) ) { y <- col2rgb(x)[, 1] x <- rgb(y[1], y[2], y[3], maxColorValue=255) } return(x) })) colours <- setNames(colours, c(polar@non_sig_name, sig_groups)) if(! inherits(polar_df, "data.frame")) { stop("polar_df must be a data frame") } if(! fc_or_zscore %in% c("zscore", "fc")) { stop("fc_or_zscore must be either 'zscore' or 'fc'") } if(! colour_scale %in% c("discrete", "continuous")) { stop("colour_scale must be either 'discrete' or 'continuous'") } if(! is.numeric(label_size)) stop('label_size must be a numeric') if(! is.numeric(continuous_shift)) { stop('continuous_shift must be a numeric') } if(! (0 <= continuous_shift & continuous_shift <= 2) ) { stop('continuous_shift must be between 0 and 2') } # Calculate the colours by significance offset <- (polar_df$angle[!is.na(polar_df$angle)] + continuous_shift/2) offset[offset > 1] <- offset[offset > 1] - 1 polar_df$hue <- hsv(offset, 1, 1) polar_df$hue[polar_df$sig == polar@non_sig_name] <- non_sig_colour volcano_toptable <- cbind(polar_df, polar@pvalues[match(rownames(polar_df), rownames(polar@pvalues)), ]) volcano_toptable$logP <- -1*log10( volcano_toptable[, paste0(polar@multi_group_test, "_pvalue")]) volcano_toptable$x <- volcano_toptable[, paste0("x_", fc_or_zscore)] volcano_toptable$y <- volcano_toptable[, paste0("y_", fc_or_zscore)] volcano_toptable$r <- volcano_toptable[, paste0("r_", fc_or_zscore)] # Create the cylindrical grid for the volcano to sit in if(is.null(grid)){ grid <- polar_grid(r_vector = volcano_toptable$r, z_vector = volcano_toptable$logP, r_axis_ticks = NULL, z_axis_ticks = NULL, ...) } else { if(inherits(grid, "grid")) stop('grid must be a grid object')} polar_grid <- grid@polar_grid axes <- grid@axes axis_labels <- grid@axis_labs h <- as.numeric(grid@z) R <- as.numeric(grid@r) axis_settings <- list(title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE, autotick = FALSE) axis_settings_xy <- list(title = "", zeroline = FALSE, showline = FALSE, showticklabels = FALSE, showgrid = FALSE, autotick = FALSE, showspikes = FALSE) volcano_toptable <- volcano_toptable[! is.na(volcano_toptable$x), ] volcano_toptable <- volcano_toptable[! is.na(volcano_toptable$y), ] volcano_toptable <- volcano_toptable[! is.na(volcano_toptable$logP), ] volcano_toptable$col <- as.character(colours[match(volcano_toptable$sig, names(colours))]) if(any(duplicated(colours))){ warning(paste("Some colours are repeated. These will be compressed", "into one significance group.")) colours <- setNames( unique(colours), unlist(lapply(unique(colours), function(x) { groups_involved <- names(colours)[colours == x] # Filter onto those included only, unless empty if(any(groups_involved %in% volcano_toptable$sig)){ groups_involved <- groups_involved[groups_involved %in% volcano_toptable$sig] } sub(",\\s+([^,]+)$", " or\n\\1", paste(groups_involved, collapse=", \n")) }))) volcano_toptable$sig <- factor(names(colours)[match( volcano_toptable$col, colours)]) } if(length(label_rows) != 0){ if(! all(is.numeric(label_rows))) { if(! all(label_rows %in% rownames(volcano_toptable))) { stop("label_rows must be in rownames(polar_df)") }} if(all(is.numeric(label_rows))) { if(! all(label_rows < nrow(volcano_toptable))) { stop("label_rows not in 1:nrow(polar_df)") }} annot <- lapply(label_rows, function(i) { row <- volcano_toptable[i, ] if(colour_code_labels) ac <- row$col else ac <- label_colour annot <- list(x = row$x, y = row$y, z = row$logP, text = row$label, textangle = 0, ax = arrow_length, ay = 0, arrowcolor = ac, font = list(color = ac), arrowwidth = 1, arrowhead = 6, arrowsize = 1.5, yanchor = "middle") }) } else {annot <- list()} axis_settings_xy[['range']] <- c(-1.05*z_axis_title_offset*(grid@r+1), 1.05*z_axis_title_offset*(grid@r+1)) p <- plot_ly(data = volcano_toptable, x = ~x, y = ~y, z = ~logP, marker = list(size = marker_size, sizemode = 'diameter', line = list(color = marker_outline_colour, width = marker_outline_width)), height = plot_height, key=~label, opacity = marker_alpha, color = ~switch(colour_scale, "discrete" = sig, "continuous" = I(hue)), hoverinfo = 'text', text = ~hover, colors = switch(colour_scale, "discrete" = colours, "continuous" = NULL), type = "scatter3d", mode = "markers", source = source) %>% # Add the cylindrical grid add_trace(x = polar_grid$x, y = polar_grid$y, z = polar_grid$z, color = I(grid_colour), line = list(width = grid_width), showlegend = FALSE, type = "scatter3d", mode = "lines", hoverinfo = "none",inherit = FALSE) %>% # Horizontal axes add_trace(x = axes$x, y = axes$y, z = 0, color = I(axis_colour), line = list(width = axis_width), showlegend = FALSE, type = "scatter3d", mode = "lines", hoverinfo = "none", inherit = FALSE) %>% add_text( x = radial_axis_title_offset*axis_labels$x*z_axis_title_offset, y = radial_axis_title_offset*axis_labels$y*z_axis_title_offset, z = 0, text = levels(polar@sampledata[, polar@contrast]), color = I(axis_colour), type = "scatter3d", mode = "text", textfont = list(size = radial_axis_title_size), textposition = 'middle center', hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% # label z axis add_text(x = c(rep(1.05*R*sinpi(axis_angle), grid@n_z_breaks), 1.2*R*z_axis_title_offset*sinpi(axis_angle)), y = c(rep(1.05*R*cospi(axis_angle), grid@n_z_breaks), 1.2*R*z_axis_title_offset*cospi(axis_angle)), z = c(grid@z_breaks, h/2)*0.95, text = c(grid@z_breaks, '-log<sub>10</sub>P'), textposition = 'middle left', textfont = list(size = z_axis_title_size), color = I(axis_colour), hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% add_trace(x = R*sinpi(axis_angle), y = R*cospi(axis_angle), z = c(0, h), color = I(axis_colour), line = list(width = axis_width), showlegend = FALSE, type = "scatter3d", mode = "lines", hoverinfo = "none", inherit = FALSE) %>% # label radial axis add_text(x = grid@text_coords$x, y = grid@text_coords$y, z = 0.05, text = grid@text_coords$text, textposition = 'top center', textfont = list(size = 10), color = I(axis_colour), hoverinfo = 'none', showlegend = FALSE, inherit = FALSE) %>% layout( margin = list(0, 0, 0, 0), paper_bgcolor = 'rgba(0, 0, 0, 0)', plot_bgcolor = 'rgba(0, 0, 0, 0)', scene = list( camera = list(eye = camera_eye), aspectratio = list(x = xy_aspectratio, y = xy_aspectratio, z = z_aspectratio), dragmode = "turntable", xaxis = axis_settings_xy, yaxis = axis_settings_xy, zaxis = axis_settings, annotations = annot ), xaxis = list(title = "x"), yaxis = list(title = "y") ) if(continue_radial_axes){ vals <- c(0, 0, NA, 2*pi/3, 2*pi/3, NA, 4*pi/3, 4*pi/3, NA) p <-p %>% add_trace(x = R*sin(pi/2 + vals), y = R*cos(pi/2 + vals), z = rep(c(0, h, NA), 3), color = I(axis_colour), line = list(width = axis_width), showlegend = FALSE, type = "scatter3d", mode = "lines", hoverinfo = "none", inherit = FALSE) } return(p) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/volcano3D_old.R
#' Convert RNA-Seq count data to a volcano3d object using 'limma voom' #' #' This function is used instead of \code{\link{polar_coords}} if you have raw #' RNA-Seq count data. The function takes a design formula, metadata and raw #' RNA-Seq count data and uses 'limma voom' to analyse the data. The results are #' converted to a 'volc3d' object ready for plotting a 3d volcano plot or polar #' plot. #' #' @param formula Design formula which must be of the form `~ 0 + outcome + #' ...`. The 3-way outcome variable must be the first variable after the '0', #' and this variable must be a factor with exactly 3 levels. #' @param metadata Matrix or dataframe containing metadata as referenced by #' `formula` #' @param counts Matrix containing raw gene expression count data #' @param pcutoff Cut-off for p-value significance #' @param padj.method Can be any method available in `p.adjust` or `"qvalue"`. #' The option "none" is a pass-through. #' @param filter_pairwise Logical whether adjusted p-value pairwise statistical #' tests are only conducted on genes which reach significant adjusted p-value #' cut-off on the group likelihood ratio test #' @param ... Optional arguments passed to \code{\link{polar_coords}} #' @return Calls \code{\link{polar_coords}} to return an S4 'volc3d' object #' @details #' Statistical results for the group and pairwise comparisons are calculated #' using the 'limma voom' pipeline and the results passed to #' \code{\link{polar_coords}} to generate a 'volc3d' object ready for plotting a #' 3d volcano plot or polar plot. #' @seealso \code{\link{polar_coords}}, \code{\link{deseq_polar}}, #' \code{\link[limma:voom]{voom}} in the limma package #' #' @examples #' if (requireNamespace("limma", quietly = TRUE) & #' requireNamespace("edgeR", quietly = TRUE)) { #' library(limma) #' library(edgeR) #' #' counts <- matrix(rnbinom(n=1500, mu=100, size=1/0.5), ncol=15) #' cond <- factor(rep(1:3, each=5), labels = c('A', 'B', 'C')) #' cond <- data.frame(cond) #' #' polar <- voom_polar(~0 + cond, cond, counts) #' #' volcano3D(polar) #' radial_ggplot(polar) #' } #' #' @importFrom stats coefficients model.matrix terms update #' @export voom_polar <- function(formula, metadata, counts, pcutoff = 0.05, padj.method = "BH", filter_pairwise = TRUE, ...) { # Check packages and input data if (!requireNamespace("edgeR", quietly = TRUE)) { stop("Can't find package edgeR. Try: BiocManager::install('edgeR')", call. = FALSE) } if (!requireNamespace("limma", quietly = TRUE)) { stop("Can't find package limma. Try: BiocManager::install('limma')", call. = FALSE) } # force formula to have no intercept if (attr(terms(formula), "intercept") != 0) formula <- update(formula, ~. -1) modterms <- attr(terms(formula), "term.labels") outcome_col <- modterms[1] if (nlevels(metadata[, outcome_col]) != 3) stop("Outcome does not have 3 levels") # Set up data vdesign <- model.matrix(formula, data = metadata) contrast_set <- list(paste0(colnames(vdesign)[1] , "-", colnames(vdesign)[2]), paste0(colnames(vdesign)[1] , "-", colnames(vdesign)[3]), paste0(colnames(vdesign)[2] , "-", colnames(vdesign)[3])) if(!exists("makeContrasts")) stop("limma package not loaded") contrast.matrix <- eval(as.call(c(as.symbol("makeContrasts"), contrast_set, levels=list(vdesign)))) dge <- edgeR::DGEList(counts = counts) keep <- edgeR::filterByExpr(dge, vdesign) dge <- dge[keep, , keep.lib.sizes = FALSE] dge <- edgeR::calcNormFactors(dge) # Perform voom v <- limma::voom(dge, vdesign, plot = FALSE) fit1 <- limma::lmFit(v, vdesign) fit <- limma::contrasts.fit(fit1, contrast.matrix) fit <- limma::eBayes(fit) contrasts <- colnames(coefficients(fit)) Pvals_limma_DE <- lapply(contrasts, function(x){ id <- which(colnames(coefficients(fit)) == x) out <- limma::topTable(fit, coef= id, number=Inf, sort.by="none") out[,c("P.Value", "logFC")] }) out <- limma::topTable(fit, coef=1:3, number=Inf, sort.by="none") Pvals_overall <- out$P.Value pvals <- cbind(Pvals_overall, Pvals_limma_DE[[1]]$P.Value, Pvals_limma_DE[[2]]$P.Value, Pvals_limma_DE[[3]]$P.Value) # Multiple testing correction LRTpadj <- qval(Pvals_overall, method = padj.method) ind <- if(filter_pairwise){ LRTpadj < pcutoff } else {rep_len(TRUE, length(LRTpadj))} pairadj <- apply(pvals[, 2:4], 2, function(res) { out <- rep_len(NA, length(LRTpadj)) out[ind] <- qval(res[ind], method = padj.method) out }) padj <- cbind(LRTpadj, pairadj) out <- polar_coords(metadata[, outcome_col], t(log2(counts[keep, ] + 1)), pvals, padj, pcutoff, ...) out@df$type <- "voom_polar" out }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/voom_polar.R
# This file contains the extra features for the initial load # Welcome message .onAttach <- function(libname, pkgname) { packageStartupMessage(paste("-----------------------", " ", "Welcome to volcano3D!", " ", "-----------------------", sep="\n")) }
/scratch/gouwar.j/cran-all/cranData/volcano3D/R/zzz.R
## ----setup, include = FALSE, echo = FALSE------------------------------------- knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE, fig.height = 7, fig.width=7, fig.align = "center") library(knitr) library(kableExtra) ## ---- echo=FALSE-------------------------------------------------------------- library(ggplot2) library(ggpubr) library(plotly) library(usethis) ## ---- eval = FALSE------------------------------------------------------------ # install.packages("volcano3D") ## ---- eval = FALSE------------------------------------------------------------ # library(devtools) # install_github("KatrionaGoldmann/volcano3D") ## ----------------------------------------------------------------------------- library(volcano3D) ## ----------------------------------------------------------------------------- data("example_data") ## ----------------------------------------------------------------------------- kable(table(syn_example_meta$Pathotype), col.names = c("Pathotype", "Count")) ## ---- echo=FALSE-------------------------------------------------------------- mytable = data.frame( outcome = c("outcome\ \n\n(required)", "Vector containing three-level factor indicating which of the three classes each sample belongs to."), data = c("data\ \n\n(required)", "A dataframe or matrix containing data to be compared between the three classes (e.g. gene expression data). Note that variables are in columns, so gene expression data will need to be transposed. This \ is used to calculate z-score and fold change, so for gene expression count data it should be \ normalised such as log transformed or variance stabilised count transformation."), pvals = c("pvals\ \n\n(optional)", "the pvals matrix which contains the statistical\ significance of probes or attributes between classes. This contains: \ \n * the first column is a group test such as one-way ANOVA or Kruskal-Wallis test. \n * columns 2-4 contain p-values one for each comparison in the sequence A vs B, A vs C, B vs C, where A, B, C are the three levels in sequence in the outcome factor. For gene expression RNA-Seq count data, conduit functions using 'limma voom' or 'DESeq' pipelines to extract p-values for \ analysis are provided in functions `deseq_polar()` and `voom_polar()`.\ If p-values are not provided by the user, they can be calculated via the `polar_coords()` function. "), padj = c("padj\ \n\n(optional)", "Matrix containing the adjusted p-values matching the pvals matrix."), pcutoff = c("pcutoff", "Cut-off for p-value significance"), scheme = c("scheme", "Vector of colours starting with non-significant attributes"), labs = c("labs", 'Optional character vector for labelling classes. Default `NULL` leads to abbreviated labels based on levels in `outcome` using `abbreviate()`. A vector of length 3 with custom abbreviated names for the outcome levels can be supplied. Otherwise a vector length 7 is expected, of the form "ns", "B+", "B+C+", "C+", "A+C+", "A+", "A+B+", where "ns" means non-significant and A, B, C refer to levels 1, 2, 3 in `outcome`, and must be in the correct order.') ) kable(t(mytable), row.names = FALSE, col.names = c("Variable", "Details")) %>% kable_styling(font_size=11) ## ----------------------------------------------------------------------------- data("example_data") syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, data = t(syn_example_rld)) ## ----eval=FALSE--------------------------------------------------------------- # library(DESeq2) # # # setup initial dataset from Tximport # dds <- DESeqDataSetFromTximport(txi = syn_txi, # colData = syn_metadata, # design = ~ Pathotype + Batch + Gender) # # initial analysis run # dds_DE <- DESeq(dds) # # likelihood ratio test on 'Pathotype' # dds_LRT <- DESeq(dds, test = "LRT", reduced = ~ Batch + Gender, parallel = TRUE) # # # create 'volc3d' class object for plotting # res <- deseq_polar(dds_DE, dds_LRT, "Pathotype") # # # plot 3d volcano plot # volcano3D(res) ## ----eval=FALSE--------------------------------------------------------------- # library(limma) # library(edgeR) # # syn_tpm <- syn_txi$counts # raw counts # # resl <- voom_polar(~ 0 + Pathotype + Batch + Gender, syn_metadata, syn_tpm) # # volcano3D(resl) ## ---- eval=FALSE-------------------------------------------------------------- # radial_plotly(syn_polar) ## ---- eval=FALSE-------------------------------------------------------------- # radial_plotly(syn_polar) %>% toWebGL() ## ---- fig.height=4.5, fig.width=7--------------------------------------------- radial_ggplot(syn_polar, marker_size = 2.3, legend_size = 10) + theme(legend.position = "right") ## ---- fig.height = 3.2, fig.width = 7----------------------------------------- plot1 <- boxplot_trio(syn_polar, value = "COBL", text_size = 7, test = "polar_padj", my_comparisons=list(c("Lymphoid", "Myeloid"), c("Lymphoid", "Fibroid"))) plot2 <- boxplot_trio(syn_polar, value = "COBL", box_colours = c("violet", "gold2"), levels_order = c("Lymphoid", "Fibroid"), text_size = 7, test = "polar_padj" ) plot3 <- boxplot_trio(syn_polar, value = "TREX2", text_size = 7, stat_size=2.5, test = "polar_multi_padj", levels_order = c("Lymphoid", "Myeloid", "Fibroid"), box_colours = c("blue", "red", "green3")) ggarrange(plot1, plot2, plot3, ncol=3) ## ---- eval=FALSE, fig.height=5------------------------------------------------ # p <- volcano3D(syn_polar) # p ## ----volcano3D, echo = FALSE, message=FALSE, fig.align='center', out.width='80%', out.extra='style="border: 0;"'---- knitr::include_graphics("volcano3D.png") ## ---- eval=FALSE-------------------------------------------------------------- # add_animation(p) ## ---- eval=FALSE-------------------------------------------------------------- # p %>% plotly::config(toImageButtonOptions = list(format = "svg")) ## ---- eval=FALSE-------------------------------------------------------------- # htmlwidgets::saveWidget(as_widget(p), "volcano3D.html") ## ----------------------------------------------------------------------------- citation("volcano3D")
/scratch/gouwar.j/cran-all/cranData/volcano3D/inst/doc/Vignette.R
--- title: "volcano3D" author: "Katriona Goldmann, Myles Lewis" output: html_document: toc: true toc_float: collapsed: false toc_depth: 3 number_sections: false vignette: > %\VignetteIndexEntry{volcano3D} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- <style> .title{ display: none; } </style> ```{r setup, include = FALSE, echo = FALSE} knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE, fig.height = 7, fig.width=7, fig.align = "center") library(knitr) library(kableExtra) ``` # volcano3D <img src="https://katrionagoldmann.github.io/volcano3D/logo.png" align="right" alt="" width="200" hspace="50" vspace="50" style="border: 0;"/> ```{r, echo=FALSE} library(ggplot2) library(ggpubr) library(plotly) library(usethis) ``` The volcano3D package provides a tool for analysis of three-class high dimensional data. It enables exploration of genes differentially expressed between three groups. Its main purpose is for the visualisation of differentially expressed genes in a three-dimensional volcano plot or three-way polar plot. These plots can be converted to interactive visualisations using plotly. The 3-way polar plots and 3d volcano plots can be applied to any data in which multiple attributes have been measured and their relative levels are being compared across three classes. This vignette covers the basic features of the package using a small example data set. To explore more extensive examples and view the interactive radial and volcano plots, see the [extended vignette](https://katrionagoldmann.github.io/volcano3D/articles/Extended_Vignette.html) which explores a case study from the PEAC rheumatoid arthritis trial (Pathobiology of Early Arthritis Cohort). The methodology has been published in [Lewis, Myles J., et al. _Molecular portraits of early rheumatoid arthritis identify clinical and treatment response phenotypes_. Cell reports 28.9 (2019): 2455-2470. (DOI: 10.1016/j.celrep.2019.07.091)](https://doi.org/10.1016/j.celrep.2019.07.091) with an interactive, searchable web tool available at [https://peac.hpc.qmul.ac.uk](https://peac.hpc.qmul.ac.uk). This was creating as an [R Shiny app](https://www.rstudio.com/products/shiny/) and deployed to the web using a server. There are also supplementary vignettes with further information on: - [using the volcano3D package to create and deploy a shiny app](https://katrionagoldmann.github.io/volcano3D/articles/shiny_builder.html) </br> [![Lifecycle: Stable](https://img.shields.io/badge/lifecycle-stable-blue.svg)](https://lifecycle.r-lib.org/articles/stages.html) [![License: GPL v2](https://img.shields.io/badge/License-GPL%20v2-mediumpurple.svg)](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html) [![CRAN status](https://www.r-pkg.org/badges/version/volcano3D)](https://cran.r-project.org/package=volcano3D) [![Downloads](https://cranlogs.r-pkg.org/badges/grand-total/volcano3D?color=orange)](https://cranlogs.r-pkg.org/badges/grand-total/volcano3D) `r paste0("[![", Sys.Date(),"]","(",paste0("https://img.shields.io/badge/last%20commit-", gsub('-', '--', Sys.Date()),"-turquoise.svg"), ")]","(",'https://github.com/KatrionaGoldmann/volcano3D/blob/master/NEWS.md',")")` [![Build](https://github.com/KatrionaGoldmann/volcano3D/actions/workflows/r.yml/badge.svg)](https://github.com/KatrionaGoldmann/volcano3D/actions/workflows/r.yml/badge.svg) [![GitHub issues](https://img.shields.io/github/issues/KatrionaGoldmann/volcano3D.svg)](https://GitHub.com/KatrionaGoldmann/volcano3D/issues/) ## Getting Started ### Prerequisites * [ggplot2](https://CRAN.R-project.org/package=ggplot2) * [ggpubr](https://CRAN.R-project.org/package=ggpubr) * [plotly](https://CRAN.R-project.org/package=plotly) ### Install from CRAN [![CRAN status](https://www.r-pkg.org/badges/version/volcano3D)](https://cran.r-project.org/package=volcano3D) ```{r, eval = FALSE} install.packages("volcano3D") ``` ### Install from Github [![GitHub tag](https://img.shields.io/github/tag/KatrionaGoldmann/volcano3D.svg)](https://GitHub.com/KatrionaGoldmann/volcano3D/tags/) ```{r, eval = FALSE} library(devtools) install_github("KatrionaGoldmann/volcano3D") ``` ### Load the package ```{r} library(volcano3D) ``` # Examples This vignette uses a subset of the 500 genes from the PEAC dataset to explore the package functions. This can be loaded using: ```{r} data("example_data") ``` Which contains: * `syn_example_rld` - the log transformed expression data * `syn_example_meta` which contains sample information and divides the samples into 3 classes. Samples in this cohort fall into three histological 'pathotype' groups: ```{r} kable(table(syn_example_meta$Pathotype), col.names = c("Pathotype", "Count")) ``` These will be used as the differential expression classes for the three-way analysis. ## Creating Polar Coordinates The function `polar_coords()` is used to map attributes to polar coordinates. If you have RNA-Seq count data this step can be skipped and you can use functions `deseq_polar()` or `voom_polar()` instead (see [Gene Expression pipeline]). `polar_coords` accepts raw data and performs all the calculations needed to generate coordinates, colours etc for plotting either a 3d volcano plot or radial 3-way plot. In brief, the function calculates the mean of each attribute/ variable for each group and maps the mean level per group onto polar coordinates along 3 axes in the x-y plane. The z axis is plotted as -log~10~(p-value) of the group statistical test (e.g. likelihood ratio test, one-way ANOVA or Kruskal-Wallis test). A table of p-values can be supplied by the user (see table below for formatting requirements). If a table of p-values is absent, p-values are automatically calculated by `polar_coords()`. By default one-way ANOVA is used for the group comparison and t-tests are used for pairwise tests. `polar_coords()` has the following inputs: ```{r, echo=FALSE} mytable = data.frame( outcome = c("outcome\ \n\n(required)", "Vector containing three-level factor indicating which of the three classes each sample belongs to."), data = c("data\ \n\n(required)", "A dataframe or matrix containing data to be compared between the three classes (e.g. gene expression data). Note that variables are in columns, so gene expression data will need to be transposed. This \ is used to calculate z-score and fold change, so for gene expression count data it should be \ normalised such as log transformed or variance stabilised count transformation."), pvals = c("pvals\ \n\n(optional)", "the pvals matrix which contains the statistical\ significance of probes or attributes between classes. This contains: \ \n * the first column is a group test such as one-way ANOVA or Kruskal-Wallis test. \n * columns 2-4 contain p-values one for each comparison in the sequence A vs B, A vs C, B vs C, where A, B, C are the three levels in sequence in the outcome factor. For gene expression RNA-Seq count data, conduit functions using 'limma voom' or 'DESeq' pipelines to extract p-values for \ analysis are provided in functions `deseq_polar()` and `voom_polar()`.\ If p-values are not provided by the user, they can be calculated via the `polar_coords()` function. "), padj = c("padj\ \n\n(optional)", "Matrix containing the adjusted p-values matching the pvals matrix."), pcutoff = c("pcutoff", "Cut-off for p-value significance"), scheme = c("scheme", "Vector of colours starting with non-significant attributes"), labs = c("labs", 'Optional character vector for labelling classes. Default `NULL` leads to abbreviated labels based on levels in `outcome` using `abbreviate()`. A vector of length 3 with custom abbreviated names for the outcome levels can be supplied. Otherwise a vector length 7 is expected, of the form "ns", "B+", "B+C+", "C+", "A+C+", "A+", "A+B+", where "ns" means non-significant and A, B, C refer to levels 1, 2, 3 in `outcome`, and must be in the correct order.') ) kable(t(mytable), row.names = FALSE, col.names = c("Variable", "Details")) %>% kable_styling(font_size=11) ``` This can be applied to the example data as below: ```{r} data("example_data") syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, data = t(syn_example_rld)) ``` This creates a 'volc3d' class object for downstream plotting. ## Gene expression pipeline RNA-Sequencing gene expression count data can be compared for differentially expressed genes between 3 classes using 2 pipeline functions to allow statistical analysis by Bioconductor packages 'DESeq2' and 'limma voom' to quickly generate a polar plotting object of class 'volc3d' which can be plotted either as a 2d polar plot with 3 axes or as a 3d cylindrical plot with a 3d volcano plot. Two functions `deseq_polar()` and `voom_polar()` are available. They both take RNA-Seq count data objects as input and extract correct statistical results and then internally call `polar_coords()` to create a 'volc3d' class object which can be plotted straightaway. ### Method using DESeq2 This takes 2 `DESeqDataSet` objects and converts the results to a 'volc3d' class object for plotting. `object` is an object of class 'DESeqDataSet' with the full design formula. Note the function `DESeq` needs to have been previously run on this object. `objectLRT` is an object of class 'DESeqDataSet' with the reduced design formula. The function `DESeq` needs to have been run on this object with `DESeq` argument `test="LRT"`. Note that in the DESeq2 design formula, the 3-class variable of interest should be first. ```{r eval=FALSE} library(DESeq2) # setup initial dataset from Tximport dds <- DESeqDataSetFromTximport(txi = syn_txi, colData = syn_metadata, design = ~ Pathotype + Batch + Gender) # initial analysis run dds_DE <- DESeq(dds) # likelihood ratio test on 'Pathotype' dds_LRT <- DESeq(dds, test = "LRT", reduced = ~ Batch + Gender, parallel = TRUE) # create 'volc3d' class object for plotting res <- deseq_polar(dds_DE, dds_LRT, "Pathotype") # plot 3d volcano plot volcano3D(res) ``` ### Method using limma voom The method for limma voom is faster and takes a design formula, metadata and raw count data. The Bioconductor packages 'limma' and 'edgeR' are used to analyse the data using the 'voom' method. The results are converted to a 'volc3d' object ready for plotting a 3d volcano plot or 3-way polar plot. Note the design formula must be of the form `~ 0 + outcome + ...`. The 3-class outcome variable must be the first variable after the '0', and this variable must be a factor with exactly 3 levels. ```{r eval=FALSE} library(limma) library(edgeR) syn_tpm <- syn_txi$counts # raw counts resl <- voom_polar(~ 0 + Pathotype + Batch + Gender, syn_metadata, syn_tpm) volcano3D(resl) ``` ## Radial Plots The differential expression can now be visualised on an interactive radial plot using `radial_plotly`. ```{r, eval=FALSE} radial_plotly(syn_polar) ``` Unfortunately CRAN does not support interactive plotly in the vignette, but these can be viewed on the [extended vignette](https://katrionagoldmann.github.io/volcano3D/articles/Extended_Vignette.html). When interactive, it is possible to identify genes for future interrogation by hovering over certain markers. `radial_plotly` produces an SVG based plotly object by default. With 10,000s of points SVG can be slow, so for large number of points we recommend switching to webGL by piping the plotly object to `toWebGL()`. ```{r, eval=FALSE} radial_plotly(syn_polar) %>% toWebGL() ``` A very similar looking static ggplot image can be created using `radial_ggplot`: ```{r, fig.height=4.5, fig.width=7} radial_ggplot(syn_polar, marker_size = 2.3, legend_size = 10) + theme(legend.position = "right") ``` ## Boxplots Any one specific variable (such as a gene) can be interrogated using a boxplot to investigate differences between groups: ```{r, fig.height = 3.2, fig.width = 7} plot1 <- boxplot_trio(syn_polar, value = "COBL", text_size = 7, test = "polar_padj", my_comparisons=list(c("Lymphoid", "Myeloid"), c("Lymphoid", "Fibroid"))) plot2 <- boxplot_trio(syn_polar, value = "COBL", box_colours = c("violet", "gold2"), levels_order = c("Lymphoid", "Fibroid"), text_size = 7, test = "polar_padj" ) plot3 <- boxplot_trio(syn_polar, value = "TREX2", text_size = 7, stat_size=2.5, test = "polar_multi_padj", levels_order = c("Lymphoid", "Myeloid", "Fibroid"), box_colours = c("blue", "red", "green3")) ggarrange(plot1, plot2, plot3, ncol=3) ``` ## 3D Volcano Plot Lastly, the 3D volcano plot can be used to project 3-way differential comparisons such as differential gene expression between 3 classes onto cylindrical polar coordinates. ```{r, eval=FALSE, fig.height=5} p <- volcano3D(syn_polar) p ``` ```{r volcano3D, echo = FALSE, message=FALSE, fig.align='center', out.width='80%', out.extra='style="border: 0;"'} knitr::include_graphics("volcano3D.png") ``` A fully interactive demonstration of this plot can be viewed at: https://peac.hpc.qmul.ac.uk/ ## Spinning Animation It is also possible to animate spinning/rotation of the plot in 3d using the `add_animation` function which adds a custom plotly modeBar button: ```{r, eval=FALSE} add_animation(p) ``` A working demo of this function can be viewed at https://peac.hpc.qmul.ac.uk/ by clicking on the 'play' button in the plotly modeBar to spin the plot. ## Saving Plotly Plots <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> ### Static Images There are a few ways to save plotly plots as static images. Firstly plotly offers a download button ( <i class="fa fa-camera" aria-hidden="true"></i> ) in the figure mode bar (appears top right). By default this saves images as png, however it is possible to convert to svg, jpeg or webp using: ```{r, eval=FALSE} p %>% plotly::config(toImageButtonOptions = list(format = "svg")) ``` ### Interactive HTML The full plotly objects can be saved to HTML by converting them to widgets and saving with the htmlwidgets package: ```{r, eval=FALSE} htmlwidgets::saveWidget(as_widget(p), "volcano3D.html") ``` --- # Citation volcano3D was developed by the bioinformatics team at the [Experimental Medicine & Rheumatology department](https://www.qmul.ac.uk/whri/emr/) and [Centre for Translational Bioinformatics](https://www.qmul.ac.uk/c4tb/) at Queen Mary University London. If you use this package please cite as: ```{r} citation("volcano3D") ``` or using: > Lewis, Myles J., et al. _Molecular portraits of early rheumatoid arthritis identify clinical and treatment response phenotypes_. Cell reports 28.9 (2019): 2455-2470.
/scratch/gouwar.j/cran-all/cranData/volcano3D/inst/doc/Vignette.rmd
## ----setup, include = FALSE, echo = FALSE------------------------------------- knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE, fig.height = 7, fig.width=7, fig.align = "center") library(knitr) library(kableExtra) ## ---- echo=FALSE-------------------------------------------------------------- library(ggplot2) library(ggpubr) library(plotly) library(usethis) ## ---- eval=FALSE-------------------------------------------------------------- # library(volcano3D) # # # Basic DESeq2 set up # library(DESeq2) # # counts <- matrix(rnbinom(n=3000, mu=100, size=1/0.5), ncol=30) # rownames(counts) <- paste0("gene", 1:100) # cond <- rep(factor(rep(1:3, each=5), labels = c('A', 'B', 'C')), 2) # resp <- factor(rep(1:2, each=15), labels = c('non.responder', 'responder')) # metadata <- data.frame(drug = cond, response = resp) # # # Full dataset object construction # dds <- DESeqDataSetFromMatrix(counts, metadata, ~response) # # # Perform 3x DESeq2 analyses comparing binary response for each drug # res <- deseq_2x3(dds, ~response, "drug") ## ---- eval=FALSE-------------------------------------------------------------- # library(easylabel) # df <- as.data.frame(res[[1]]) # results for the first drug # easyVolcano(df) ## ---- eval=FALSE-------------------------------------------------------------- # # Generate polar object # obj <- deseq_2x3_polar(res) # # # 2d plot # radial_plotly(obj) # # # 3d plot # volcano3D(obj) ## ---- eval=FALSE-------------------------------------------------------------- # obj <- deseq_2x3_polar(data1) # labs <- c('MS4A1', 'TNXA', 'FLG2', 'MYBPC1') # radial_plotly(obj, type=2, label_rows = labs) %>% toWebGL() ## ----radial_2x3_pos, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'---- knitr::include_graphics("radial_2x3_pos.png") ## ----volc_2x3, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'---- knitr::include_graphics("volc3d_2x3.png") ## ---- eval=FALSE-------------------------------------------------------------- # obj <- deseq_2x3_polar(data1, process = "negative") # labs <- c('MS4A1', 'TNXA', 'FLG2', 'MYBPC1') # radial_plotly(obj, type=2, label_rows = labs) %>% toWebGL() ## ----radial_2x3_neg, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'---- knitr::include_graphics("radial_2x3_neg.png") ## ----eval=FALSE--------------------------------------------------------------- # polar_obj <- polar_coords_2x3(vstdata, metadata, "ACR.response.status", # "Randomised.Medication") # # radial_plotly(polar_obj, type=2) # volcano3D(polar_obj) ## ---- eval=FALSE-------------------------------------------------------------- # forest_ggplot(obj, c("MS4A1", "FLG2", "SFN") ## ----forest, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'---- knitr::include_graphics("forest.png") ## ----------------------------------------------------------------------------- citation("volcano3D")
/scratch/gouwar.j/cran-all/cranData/volcano3D/inst/doc/Vignette_2x3.R
--- title: "volcano3D: 2x3-way analysis" author: "Myles Lewis, Katriona Goldmann, Elisabetta Sciacca" output: html_document: toc: true toc_float: collapsed: false toc_depth: 3 number_sections: false vignette: > %\VignetteIndexEntry{2x3-way analysis} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- <style> .title{ display: none; } </style> ```{r setup, include = FALSE, echo = FALSE} knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE, fig.height = 7, fig.width=7, fig.align = "center") library(knitr) library(kableExtra) ``` ## 2x3-way analysis <img src="https://katrionagoldmann.github.io/volcano3D/logo.png" align="right" alt="" width="200" hspace="50" vspace="50" style="border: 0;"/> ```{r, echo=FALSE} library(ggplot2) library(ggpubr) library(plotly) library(usethis) ``` The main work flow for using volcano3D is ideal for comparing high dimensional data such as gene expression or other biological data across 3 classes, and this is covered in the main vignette. However, an alternative use of 3-way radial plots and 3d volcano plots is for 2x3-way analysis. In this type of analysis there is a binary factor such as drug response (responders vs non-responders) and a 2nd factor with 3 classes such as a trial with 3 drugs. ## Example This vignette shows analysis from the STRAP trial in rheumatoid arthritis, in which patients were randomised to one of three drugs (etanercept, rituximab, tocilizumab). Clinical response to treatment (a binary outcome) was measured after 16 weeks. Gene expression data from RNA-Sequencing (RNA-Seq) of synovial biopsies from the patients' inflamed joints was performed at baseline. RNA-Seq data is count based and overdispersed, and thus is typically best modelled by a negative binomial distribution. ## DESeq2 pipeline Differential gene expression to compare the synovial gene expression between responders vs non-responders is performed using the Bioconductor package DESeq2. Since there are 3 distinct drugs this becomes a 2x3-factor analysis. The following code shows set up and 2x3-way analysis in DESeq2 followed by generation of a 'volc3d' class results object for plotting and visualisation of the results. ```{r, eval=FALSE} library(volcano3D) # Basic DESeq2 set up library(DESeq2) counts <- matrix(rnbinom(n=3000, mu=100, size=1/0.5), ncol=30) rownames(counts) <- paste0("gene", 1:100) cond <- rep(factor(rep(1:3, each=5), labels = c('A', 'B', 'C')), 2) resp <- factor(rep(1:2, each=15), labels = c('non.responder', 'responder')) metadata <- data.frame(drug = cond, response = resp) # Full dataset object construction dds <- DESeqDataSetFromMatrix(counts, metadata, ~response) # Perform 3x DESeq2 analyses comparing binary response for each drug res <- deseq_2x3(dds, ~response, "drug") ``` The design formula can contain covariates, however the main contrast should be the last term of the formula as is standard in DESeq2 analysis. The function `deseq_2x3()` returns a list of 3 DESeq2 objects containing the response analysis for each of the three drugs. These response vs non-response differential expression comparisons can be quickly visualised with the `easyVolcano()` function from the R package `easylabel`, which is designed for DESeq2 and limma objects and uses an interactive R/shiny interface. ```{r, eval=FALSE} library(easylabel) df <- as.data.frame(res[[1]]) # results for the first drug easyVolcano(df) ``` The `deseq_2x3` output is passed to `deseq_2x3_polar()` to generate a `volc3d` class object for plotting. Thus the 3-way radial plot and 3d volcano plot simplify visualisation of the 2x3-way analysis, replacing 3 volcano plots with a single radial plot or 3d volcano plot. ```{r, eval=FALSE} # Generate polar object obj <- deseq_2x3_polar(res) # 2d plot radial_plotly(obj) # 3d plot volcano3D(obj) ``` ## Real world example The example below using real data from the STRAP trial demonstrates a 3-way radial plot highlighting the relationship between genes significantly increased in responders across each of the three drugs. The pipe to `toWebGL()` is used to speed up plotting by using webGL instead of SVG in plotly scatter plots. Alternatively, a ggplot2 version can be plotted using `radial_ggplot()`. ```{r, eval=FALSE} obj <- deseq_2x3_polar(data1) labs <- c('MS4A1', 'TNXA', 'FLG2', 'MYBPC1') radial_plotly(obj, type=2, label_rows = labs) %>% toWebGL() ``` ```{r radial_2x3_pos, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'} knitr::include_graphics("radial_2x3_pos.png") ``` A 3d volcano plot can be generated too. ```{r volc_2x3, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'} knitr::include_graphics("volc3d_2x3.png") ``` To show genes which are significantly increased in non-responders for each drug, we reprocess the object using the argument `process = "negative"` as this leads to a different colour scheme for each gene. The polar coordinates are essentially flipped as each axis represents increased expression in non-responders. ```{r, eval=FALSE} obj <- deseq_2x3_polar(data1, process = "negative") labs <- c('MS4A1', 'TNXA', 'FLG2', 'MYBPC1') radial_plotly(obj, type=2, label_rows = labs) %>% toWebGL() ``` ```{r radial_2x3_neg, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'} knitr::include_graphics("radial_2x3_neg.png") ``` ## Custom 2x3-way analysis The above workflow is designed for RNA-Seq count data. For other raw data types, the function `polar_coords_2x3()` is used to map attributes to polar coordinates in a 2x3-way analysis. ```{r eval=FALSE} polar_obj <- polar_coords_2x3(vstdata, metadata, "ACR.response.status", "Randomised.Medication") radial_plotly(polar_obj, type=2) volcano3D(polar_obj) ``` In the above code example `vstdata` contains transformed (approximately Gaussian) gene expression data with genes in columns and samples in rows. `metadata` is a dataframe of sample information with samples in rows. `"ACR.response.status"` refers the the binary response column in `metadata`. `"Randomised.Medication"` refers to the 3-way group column in `metadata`. `polar_coords_2x3()` accepts raw data and performs all the calculations needed to generate coordinates, colours etc for plotting radial 3-way plots or 3d volcano plots. This differs from the original `polar_coords()` function in that it is the mean difference between the 2-way response outcome which is used to map coordinates along each axis for each of the 3 groups for unscaled polar coordinates. Scaled polar coordinates are generated using the *t*-statistic for each group comparison. There is no straightforward equivalent of a one-way ANOVA or likelihood ratio test to use for the *z* axis as is used in the simpler 3-way analysis for standard 3-way radial plots/ 3d volcano plots. So instead the *z* axis in a 2x3-way analysis uses the smallest p-value from each of the 3 paired comparisons. This p-value is transformed as usual as -log~10~(p). A table of p-values can be supplied by the user. But if a table of p-values is absent, p-values are automatically calculated by `polar_coords_2x3()`. Each of the 3 groups is subsetted and pairwise comparisons of the binary response factor are performed. Options here include unpaired *t*-test and Wilcoxon test (see `calc_stats_2x3()`). The colour scheme is not as straightforward as for the standard polar plot and volcano3D plot since genes (or attributes) can be significantly up or downregulated in the response comparison for each of the 3 groups. `process = "positive"` means that genes are labelled with colours if a gene is significantly upregulated in the response for that group. This uses the primary colours (RGB) so that if a gene is upregulated in both red and blue group it becomes purple etc with secondary colours. If the gene is upregulated in all 3 groups it is labelled black. Non-significant genes are in grey. With `process = "negative"` genes are coloured when they are significantly downregulated. With `process = "two.sided"` the colour scheme means that both significantly up- and down-regulated genes are coloured with down-regulated genes labelled with inverted colours (i.e. cyan is the inverse of red etc). However, significant upregulation in a group takes precedence. With `process = "negative"` the polar coordinates are also flipped as each axis now represents upregulated expression in non-responders. The end result is a `volc3d` class object for downstream plotting. ## Forest plots Specific genes/variables can be interrogated using a forest plot to investigate differences in binary response between the 3 groups. ```{r, eval=FALSE} forest_ggplot(obj, c("MS4A1", "FLG2", "SFN") ``` ```{r forest, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'} knitr::include_graphics("forest.png") ``` The related functions `forest_plot()` and `forest_plotly()` can be used to generate plots in base graphics or plotly. --- ## Citation volcano3D was developed by the bioinformatics team at the [Experimental Medicine & Rheumatology department](https://www.qmul.ac.uk/whri/emr/) and [Centre for Translational Bioinformatics](https://www.qmul.ac.uk/c4tb/) at Queen Mary University London. If you use this package please cite as: ```{r} citation("volcano3D") ``` or using: > Lewis, Myles J., et al. _Molecular portraits of early rheumatoid arthritis identify clinical and treatment response phenotypes_. Cell reports 28.9 (2019): 2455-2470.
/scratch/gouwar.j/cran-all/cranData/volcano3D/inst/doc/Vignette_2x3.Rmd
--- title: "volcano3D" author: "Katriona Goldmann, Myles Lewis" output: html_document: toc: true toc_float: collapsed: false toc_depth: 3 number_sections: false vignette: > %\VignetteIndexEntry{volcano3D} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- <style> .title{ display: none; } </style> ```{r setup, include = FALSE, echo = FALSE} knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE, fig.height = 7, fig.width=7, fig.align = "center") library(knitr) library(kableExtra) ``` # volcano3D <img src="https://katrionagoldmann.github.io/volcano3D/logo.png" align="right" alt="" width="200" hspace="50" vspace="50" style="border: 0;"/> ```{r, echo=FALSE} library(ggplot2) library(ggpubr) library(plotly) library(usethis) ``` The volcano3D package provides a tool for analysis of three-class high dimensional data. It enables exploration of genes differentially expressed between three groups. Its main purpose is for the visualisation of differentially expressed genes in a three-dimensional volcano plot or three-way polar plot. These plots can be converted to interactive visualisations using plotly. The 3-way polar plots and 3d volcano plots can be applied to any data in which multiple attributes have been measured and their relative levels are being compared across three classes. This vignette covers the basic features of the package using a small example data set. To explore more extensive examples and view the interactive radial and volcano plots, see the [extended vignette](https://katrionagoldmann.github.io/volcano3D/articles/Extended_Vignette.html) which explores a case study from the PEAC rheumatoid arthritis trial (Pathobiology of Early Arthritis Cohort). The methodology has been published in [Lewis, Myles J., et al. _Molecular portraits of early rheumatoid arthritis identify clinical and treatment response phenotypes_. Cell reports 28.9 (2019): 2455-2470. (DOI: 10.1016/j.celrep.2019.07.091)](https://doi.org/10.1016/j.celrep.2019.07.091) with an interactive, searchable web tool available at [https://peac.hpc.qmul.ac.uk](https://peac.hpc.qmul.ac.uk). This was creating as an [R Shiny app](https://www.rstudio.com/products/shiny/) and deployed to the web using a server. There are also supplementary vignettes with further information on: - [using the volcano3D package to create and deploy a shiny app](https://katrionagoldmann.github.io/volcano3D/articles/shiny_builder.html) </br> [![Lifecycle: Stable](https://img.shields.io/badge/lifecycle-stable-blue.svg)](https://lifecycle.r-lib.org/articles/stages.html) [![License: GPL v2](https://img.shields.io/badge/License-GPL%20v2-mediumpurple.svg)](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html) [![CRAN status](https://www.r-pkg.org/badges/version/volcano3D)](https://cran.r-project.org/package=volcano3D) [![Downloads](https://cranlogs.r-pkg.org/badges/grand-total/volcano3D?color=orange)](https://cranlogs.r-pkg.org/badges/grand-total/volcano3D) `r paste0("[![", Sys.Date(),"]","(",paste0("https://img.shields.io/badge/last%20commit-", gsub('-', '--', Sys.Date()),"-turquoise.svg"), ")]","(",'https://github.com/KatrionaGoldmann/volcano3D/blob/master/NEWS.md',")")` [![Build](https://github.com/KatrionaGoldmann/volcano3D/actions/workflows/r.yml/badge.svg)](https://github.com/KatrionaGoldmann/volcano3D/actions/workflows/r.yml/badge.svg) [![GitHub issues](https://img.shields.io/github/issues/KatrionaGoldmann/volcano3D.svg)](https://GitHub.com/KatrionaGoldmann/volcano3D/issues/) ## Getting Started ### Prerequisites * [ggplot2](https://CRAN.R-project.org/package=ggplot2) * [ggpubr](https://CRAN.R-project.org/package=ggpubr) * [plotly](https://CRAN.R-project.org/package=plotly) ### Install from CRAN [![CRAN status](https://www.r-pkg.org/badges/version/volcano3D)](https://cran.r-project.org/package=volcano3D) ```{r, eval = FALSE} install.packages("volcano3D") ``` ### Install from Github [![GitHub tag](https://img.shields.io/github/tag/KatrionaGoldmann/volcano3D.svg)](https://GitHub.com/KatrionaGoldmann/volcano3D/tags/) ```{r, eval = FALSE} library(devtools) install_github("KatrionaGoldmann/volcano3D") ``` ### Load the package ```{r} library(volcano3D) ``` # Examples This vignette uses a subset of the 500 genes from the PEAC dataset to explore the package functions. This can be loaded using: ```{r} data("example_data") ``` Which contains: * `syn_example_rld` - the log transformed expression data * `syn_example_meta` which contains sample information and divides the samples into 3 classes. Samples in this cohort fall into three histological 'pathotype' groups: ```{r} kable(table(syn_example_meta$Pathotype), col.names = c("Pathotype", "Count")) ``` These will be used as the differential expression classes for the three-way analysis. ## Creating Polar Coordinates The function `polar_coords()` is used to map attributes to polar coordinates. If you have RNA-Seq count data this step can be skipped and you can use functions `deseq_polar()` or `voom_polar()` instead (see [Gene Expression pipeline]). `polar_coords` accepts raw data and performs all the calculations needed to generate coordinates, colours etc for plotting either a 3d volcano plot or radial 3-way plot. In brief, the function calculates the mean of each attribute/ variable for each group and maps the mean level per group onto polar coordinates along 3 axes in the x-y plane. The z axis is plotted as -log~10~(p-value) of the group statistical test (e.g. likelihood ratio test, one-way ANOVA or Kruskal-Wallis test). A table of p-values can be supplied by the user (see table below for formatting requirements). If a table of p-values is absent, p-values are automatically calculated by `polar_coords()`. By default one-way ANOVA is used for the group comparison and t-tests are used for pairwise tests. `polar_coords()` has the following inputs: ```{r, echo=FALSE} mytable = data.frame( outcome = c("outcome\ \n\n(required)", "Vector containing three-level factor indicating which of the three classes each sample belongs to."), data = c("data\ \n\n(required)", "A dataframe or matrix containing data to be compared between the three classes (e.g. gene expression data). Note that variables are in columns, so gene expression data will need to be transposed. This \ is used to calculate z-score and fold change, so for gene expression count data it should be \ normalised such as log transformed or variance stabilised count transformation."), pvals = c("pvals\ \n\n(optional)", "the pvals matrix which contains the statistical\ significance of probes or attributes between classes. This contains: \ \n * the first column is a group test such as one-way ANOVA or Kruskal-Wallis test. \n * columns 2-4 contain p-values one for each comparison in the sequence A vs B, A vs C, B vs C, where A, B, C are the three levels in sequence in the outcome factor. For gene expression RNA-Seq count data, conduit functions using 'limma voom' or 'DESeq' pipelines to extract p-values for \ analysis are provided in functions `deseq_polar()` and `voom_polar()`.\ If p-values are not provided by the user, they can be calculated via the `polar_coords()` function. "), padj = c("padj\ \n\n(optional)", "Matrix containing the adjusted p-values matching the pvals matrix."), pcutoff = c("pcutoff", "Cut-off for p-value significance"), scheme = c("scheme", "Vector of colours starting with non-significant attributes"), labs = c("labs", 'Optional character vector for labelling classes. Default `NULL` leads to abbreviated labels based on levels in `outcome` using `abbreviate()`. A vector of length 3 with custom abbreviated names for the outcome levels can be supplied. Otherwise a vector length 7 is expected, of the form "ns", "B+", "B+C+", "C+", "A+C+", "A+", "A+B+", where "ns" means non-significant and A, B, C refer to levels 1, 2, 3 in `outcome`, and must be in the correct order.') ) kable(t(mytable), row.names = FALSE, col.names = c("Variable", "Details")) %>% kable_styling(font_size=11) ``` This can be applied to the example data as below: ```{r} data("example_data") syn_polar <- polar_coords(outcome = syn_example_meta$Pathotype, data = t(syn_example_rld)) ``` This creates a 'volc3d' class object for downstream plotting. ## Gene expression pipeline RNA-Sequencing gene expression count data can be compared for differentially expressed genes between 3 classes using 2 pipeline functions to allow statistical analysis by Bioconductor packages 'DESeq2' and 'limma voom' to quickly generate a polar plotting object of class 'volc3d' which can be plotted either as a 2d polar plot with 3 axes or as a 3d cylindrical plot with a 3d volcano plot. Two functions `deseq_polar()` and `voom_polar()` are available. They both take RNA-Seq count data objects as input and extract correct statistical results and then internally call `polar_coords()` to create a 'volc3d' class object which can be plotted straightaway. ### Method using DESeq2 This takes 2 `DESeqDataSet` objects and converts the results to a 'volc3d' class object for plotting. `object` is an object of class 'DESeqDataSet' with the full design formula. Note the function `DESeq` needs to have been previously run on this object. `objectLRT` is an object of class 'DESeqDataSet' with the reduced design formula. The function `DESeq` needs to have been run on this object with `DESeq` argument `test="LRT"`. Note that in the DESeq2 design formula, the 3-class variable of interest should be first. ```{r eval=FALSE} library(DESeq2) # setup initial dataset from Tximport dds <- DESeqDataSetFromTximport(txi = syn_txi, colData = syn_metadata, design = ~ Pathotype + Batch + Gender) # initial analysis run dds_DE <- DESeq(dds) # likelihood ratio test on 'Pathotype' dds_LRT <- DESeq(dds, test = "LRT", reduced = ~ Batch + Gender, parallel = TRUE) # create 'volc3d' class object for plotting res <- deseq_polar(dds_DE, dds_LRT, "Pathotype") # plot 3d volcano plot volcano3D(res) ``` ### Method using limma voom The method for limma voom is faster and takes a design formula, metadata and raw count data. The Bioconductor packages 'limma' and 'edgeR' are used to analyse the data using the 'voom' method. The results are converted to a 'volc3d' object ready for plotting a 3d volcano plot or 3-way polar plot. Note the design formula must be of the form `~ 0 + outcome + ...`. The 3-class outcome variable must be the first variable after the '0', and this variable must be a factor with exactly 3 levels. ```{r eval=FALSE} library(limma) library(edgeR) syn_tpm <- syn_txi$counts # raw counts resl <- voom_polar(~ 0 + Pathotype + Batch + Gender, syn_metadata, syn_tpm) volcano3D(resl) ``` ## Radial Plots The differential expression can now be visualised on an interactive radial plot using `radial_plotly`. ```{r, eval=FALSE} radial_plotly(syn_polar) ``` Unfortunately CRAN does not support interactive plotly in the vignette, but these can be viewed on the [extended vignette](https://katrionagoldmann.github.io/volcano3D/articles/Extended_Vignette.html). When interactive, it is possible to identify genes for future interrogation by hovering over certain markers. `radial_plotly` produces an SVG based plotly object by default. With 10,000s of points SVG can be slow, so for large number of points we recommend switching to webGL by piping the plotly object to `toWebGL()`. ```{r, eval=FALSE} radial_plotly(syn_polar) %>% toWebGL() ``` A very similar looking static ggplot image can be created using `radial_ggplot`: ```{r, fig.height=4.5, fig.width=7} radial_ggplot(syn_polar, marker_size = 2.3, legend_size = 10) + theme(legend.position = "right") ``` ## Boxplots Any one specific variable (such as a gene) can be interrogated using a boxplot to investigate differences between groups: ```{r, fig.height = 3.2, fig.width = 7} plot1 <- boxplot_trio(syn_polar, value = "COBL", text_size = 7, test = "polar_padj", my_comparisons=list(c("Lymphoid", "Myeloid"), c("Lymphoid", "Fibroid"))) plot2 <- boxplot_trio(syn_polar, value = "COBL", box_colours = c("violet", "gold2"), levels_order = c("Lymphoid", "Fibroid"), text_size = 7, test = "polar_padj" ) plot3 <- boxplot_trio(syn_polar, value = "TREX2", text_size = 7, stat_size=2.5, test = "polar_multi_padj", levels_order = c("Lymphoid", "Myeloid", "Fibroid"), box_colours = c("blue", "red", "green3")) ggarrange(plot1, plot2, plot3, ncol=3) ``` ## 3D Volcano Plot Lastly, the 3D volcano plot can be used to project 3-way differential comparisons such as differential gene expression between 3 classes onto cylindrical polar coordinates. ```{r, eval=FALSE, fig.height=5} p <- volcano3D(syn_polar) p ``` ```{r volcano3D, echo = FALSE, message=FALSE, fig.align='center', out.width='80%', out.extra='style="border: 0;"'} knitr::include_graphics("volcano3D.png") ``` A fully interactive demonstration of this plot can be viewed at: https://peac.hpc.qmul.ac.uk/ ## Spinning Animation It is also possible to animate spinning/rotation of the plot in 3d using the `add_animation` function which adds a custom plotly modeBar button: ```{r, eval=FALSE} add_animation(p) ``` A working demo of this function can be viewed at https://peac.hpc.qmul.ac.uk/ by clicking on the 'play' button in the plotly modeBar to spin the plot. ## Saving Plotly Plots <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> ### Static Images There are a few ways to save plotly plots as static images. Firstly plotly offers a download button ( <i class="fa fa-camera" aria-hidden="true"></i> ) in the figure mode bar (appears top right). By default this saves images as png, however it is possible to convert to svg, jpeg or webp using: ```{r, eval=FALSE} p %>% plotly::config(toImageButtonOptions = list(format = "svg")) ``` ### Interactive HTML The full plotly objects can be saved to HTML by converting them to widgets and saving with the htmlwidgets package: ```{r, eval=FALSE} htmlwidgets::saveWidget(as_widget(p), "volcano3D.html") ``` --- # Citation volcano3D was developed by the bioinformatics team at the [Experimental Medicine & Rheumatology department](https://www.qmul.ac.uk/whri/emr/) and [Centre for Translational Bioinformatics](https://www.qmul.ac.uk/c4tb/) at Queen Mary University London. If you use this package please cite as: ```{r} citation("volcano3D") ``` or using: > Lewis, Myles J., et al. _Molecular portraits of early rheumatoid arthritis identify clinical and treatment response phenotypes_. Cell reports 28.9 (2019): 2455-2470.
/scratch/gouwar.j/cran-all/cranData/volcano3D/vignettes/Vignette.rmd
--- title: "volcano3D: 2x3-way analysis" author: "Myles Lewis, Katriona Goldmann, Elisabetta Sciacca" output: html_document: toc: true toc_float: collapsed: false toc_depth: 3 number_sections: false vignette: > %\VignetteIndexEntry{2x3-way analysis} %\VignetteEngine{knitr::rmarkdown} \usepackage[utf8]{inputenc} --- <style> .title{ display: none; } </style> ```{r setup, include = FALSE, echo = FALSE} knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE, fig.height = 7, fig.width=7, fig.align = "center") library(knitr) library(kableExtra) ``` ## 2x3-way analysis <img src="https://katrionagoldmann.github.io/volcano3D/logo.png" align="right" alt="" width="200" hspace="50" vspace="50" style="border: 0;"/> ```{r, echo=FALSE} library(ggplot2) library(ggpubr) library(plotly) library(usethis) ``` The main work flow for using volcano3D is ideal for comparing high dimensional data such as gene expression or other biological data across 3 classes, and this is covered in the main vignette. However, an alternative use of 3-way radial plots and 3d volcano plots is for 2x3-way analysis. In this type of analysis there is a binary factor such as drug response (responders vs non-responders) and a 2nd factor with 3 classes such as a trial with 3 drugs. ## Example This vignette shows analysis from the STRAP trial in rheumatoid arthritis, in which patients were randomised to one of three drugs (etanercept, rituximab, tocilizumab). Clinical response to treatment (a binary outcome) was measured after 16 weeks. Gene expression data from RNA-Sequencing (RNA-Seq) of synovial biopsies from the patients' inflamed joints was performed at baseline. RNA-Seq data is count based and overdispersed, and thus is typically best modelled by a negative binomial distribution. ## DESeq2 pipeline Differential gene expression to compare the synovial gene expression between responders vs non-responders is performed using the Bioconductor package DESeq2. Since there are 3 distinct drugs this becomes a 2x3-factor analysis. The following code shows set up and 2x3-way analysis in DESeq2 followed by generation of a 'volc3d' class results object for plotting and visualisation of the results. ```{r, eval=FALSE} library(volcano3D) # Basic DESeq2 set up library(DESeq2) counts <- matrix(rnbinom(n=3000, mu=100, size=1/0.5), ncol=30) rownames(counts) <- paste0("gene", 1:100) cond <- rep(factor(rep(1:3, each=5), labels = c('A', 'B', 'C')), 2) resp <- factor(rep(1:2, each=15), labels = c('non.responder', 'responder')) metadata <- data.frame(drug = cond, response = resp) # Full dataset object construction dds <- DESeqDataSetFromMatrix(counts, metadata, ~response) # Perform 3x DESeq2 analyses comparing binary response for each drug res <- deseq_2x3(dds, ~response, "drug") ``` The design formula can contain covariates, however the main contrast should be the last term of the formula as is standard in DESeq2 analysis. The function `deseq_2x3()` returns a list of 3 DESeq2 objects containing the response analysis for each of the three drugs. These response vs non-response differential expression comparisons can be quickly visualised with the `easyVolcano()` function from the R package `easylabel`, which is designed for DESeq2 and limma objects and uses an interactive R/shiny interface. ```{r, eval=FALSE} library(easylabel) df <- as.data.frame(res[[1]]) # results for the first drug easyVolcano(df) ``` The `deseq_2x3` output is passed to `deseq_2x3_polar()` to generate a `volc3d` class object for plotting. Thus the 3-way radial plot and 3d volcano plot simplify visualisation of the 2x3-way analysis, replacing 3 volcano plots with a single radial plot or 3d volcano plot. ```{r, eval=FALSE} # Generate polar object obj <- deseq_2x3_polar(res) # 2d plot radial_plotly(obj) # 3d plot volcano3D(obj) ``` ## Real world example The example below using real data from the STRAP trial demonstrates a 3-way radial plot highlighting the relationship between genes significantly increased in responders across each of the three drugs. The pipe to `toWebGL()` is used to speed up plotting by using webGL instead of SVG in plotly scatter plots. Alternatively, a ggplot2 version can be plotted using `radial_ggplot()`. ```{r, eval=FALSE} obj <- deseq_2x3_polar(data1) labs <- c('MS4A1', 'TNXA', 'FLG2', 'MYBPC1') radial_plotly(obj, type=2, label_rows = labs) %>% toWebGL() ``` ```{r radial_2x3_pos, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'} knitr::include_graphics("radial_2x3_pos.png") ``` A 3d volcano plot can be generated too. ```{r volc_2x3, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'} knitr::include_graphics("volc3d_2x3.png") ``` To show genes which are significantly increased in non-responders for each drug, we reprocess the object using the argument `process = "negative"` as this leads to a different colour scheme for each gene. The polar coordinates are essentially flipped as each axis represents increased expression in non-responders. ```{r, eval=FALSE} obj <- deseq_2x3_polar(data1, process = "negative") labs <- c('MS4A1', 'TNXA', 'FLG2', 'MYBPC1') radial_plotly(obj, type=2, label_rows = labs) %>% toWebGL() ``` ```{r radial_2x3_neg, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'} knitr::include_graphics("radial_2x3_neg.png") ``` ## Custom 2x3-way analysis The above workflow is designed for RNA-Seq count data. For other raw data types, the function `polar_coords_2x3()` is used to map attributes to polar coordinates in a 2x3-way analysis. ```{r eval=FALSE} polar_obj <- polar_coords_2x3(vstdata, metadata, "ACR.response.status", "Randomised.Medication") radial_plotly(polar_obj, type=2) volcano3D(polar_obj) ``` In the above code example `vstdata` contains transformed (approximately Gaussian) gene expression data with genes in columns and samples in rows. `metadata` is a dataframe of sample information with samples in rows. `"ACR.response.status"` refers the the binary response column in `metadata`. `"Randomised.Medication"` refers to the 3-way group column in `metadata`. `polar_coords_2x3()` accepts raw data and performs all the calculations needed to generate coordinates, colours etc for plotting radial 3-way plots or 3d volcano plots. This differs from the original `polar_coords()` function in that it is the mean difference between the 2-way response outcome which is used to map coordinates along each axis for each of the 3 groups for unscaled polar coordinates. Scaled polar coordinates are generated using the *t*-statistic for each group comparison. There is no straightforward equivalent of a one-way ANOVA or likelihood ratio test to use for the *z* axis as is used in the simpler 3-way analysis for standard 3-way radial plots/ 3d volcano plots. So instead the *z* axis in a 2x3-way analysis uses the smallest p-value from each of the 3 paired comparisons. This p-value is transformed as usual as -log~10~(p). A table of p-values can be supplied by the user. But if a table of p-values is absent, p-values are automatically calculated by `polar_coords_2x3()`. Each of the 3 groups is subsetted and pairwise comparisons of the binary response factor are performed. Options here include unpaired *t*-test and Wilcoxon test (see `calc_stats_2x3()`). The colour scheme is not as straightforward as for the standard polar plot and volcano3D plot since genes (or attributes) can be significantly up or downregulated in the response comparison for each of the 3 groups. `process = "positive"` means that genes are labelled with colours if a gene is significantly upregulated in the response for that group. This uses the primary colours (RGB) so that if a gene is upregulated in both red and blue group it becomes purple etc with secondary colours. If the gene is upregulated in all 3 groups it is labelled black. Non-significant genes are in grey. With `process = "negative"` genes are coloured when they are significantly downregulated. With `process = "two.sided"` the colour scheme means that both significantly up- and down-regulated genes are coloured with down-regulated genes labelled with inverted colours (i.e. cyan is the inverse of red etc). However, significant upregulation in a group takes precedence. With `process = "negative"` the polar coordinates are also flipped as each axis now represents upregulated expression in non-responders. The end result is a `volc3d` class object for downstream plotting. ## Forest plots Specific genes/variables can be interrogated using a forest plot to investigate differences in binary response between the 3 groups. ```{r, eval=FALSE} forest_ggplot(obj, c("MS4A1", "FLG2", "SFN") ``` ```{r forest, echo = FALSE, message=FALSE, fig.align='center', out.width='70%', out.extra='style="border: 0;"'} knitr::include_graphics("forest.png") ``` The related functions `forest_plot()` and `forest_plotly()` can be used to generate plots in base graphics or plotly. --- ## Citation volcano3D was developed by the bioinformatics team at the [Experimental Medicine & Rheumatology department](https://www.qmul.ac.uk/whri/emr/) and [Centre for Translational Bioinformatics](https://www.qmul.ac.uk/c4tb/) at Queen Mary University London. If you use this package please cite as: ```{r} citation("volcano3D") ``` or using: > Lewis, Myles J., et al. _Molecular portraits of early rheumatoid arthritis identify clinical and treatment response phenotypes_. Cell reports 28.9 (2019): 2455-2470.
/scratch/gouwar.j/cran-all/cranData/volcano3D/vignettes/Vignette_2x3.Rmd
#' Get Summary AE Statistics #' #' Compares reference and comparison groups to calculate group-wise metrics and p-values for use in AE volcano plot. #' #' @param settings Named list of settings (see examples below for standard list) #' @param dfAE Adverse events dataset structured as 1 record per adverse event #' per subject #' @param dfDemog Subject-level dataset #' @param stat Statistic to calculate for AE plot. Options are risk ratio ("RR" #' or "Risk Ratio"), risk difference ("RD" or "Risk Difference"). Defaults to #' "Risk Ratio". #' #' @return a data frame of group-wise statistics for use in the volcano plot #' #' @examples #' settings<-list( #' stratification_col="AEBODSYS", #' group_col="ARM", #' reference_group="Placebo", #' comparison_group="Xanomeline High Dose", #' id_col="USUBJID" #' ) #' getStats(dfAE=safetyData::adam_adae, dfDemog = safetyData::adam_adsl, settings) #' #' @import dplyr #' @import tidyr #' @importFrom fmsb riskratio riskdifference #' #' @export getStats <- function(dfAE, dfDemog, settings, stat="Risk Ratio") { ## Prepare data dfDemog <- dfDemog %>% select(settings[["id_col"]], settings[["group_col"]]) anly <- dfDemog %>% left_join(dfAE) # left join to keep all rows in dm (even if there were no AEs) aeCounts <- list() # count n of comparison group N_comparison <- dfDemog %>% filter(.data[[settings$group_col]] == settings$comparison_group) %>% pull(.data[[settings$id_col]]) %>% unique() %>% length() # count n of reference group N_ref <- dfDemog %>% filter(.data[[settings$group_col]] == settings$reference_group) %>% pull(.data[[settings$id_col]]) %>% unique() %>% length() # create table of numbers for doing stats aeCounts <- anly %>% filter(.data[[settings$group_col]] %in% c(settings$comparison_group, settings$reference_group)) %>% group_by(.data[[settings$stratification_col]], .data[[settings$group_col]]) %>% # summarize(event=n())%>% do we need this too? summarize(event = length(unique(.data[[settings$id_col]]))) %>% ungroup() %>% stats::na.omit() %>% pivot_wider( names_from = .data[[settings$group_col]], values_from = "event", values_fill = 0 ) %>% rename( strata = settings$stratification_col, eventN_comparison = settings$comparison_group, eventN_ref = settings$reference_group ) %>% mutate( eventN_total = .data$eventN_comparison + .data$eventN_ref, N_comparison = N_comparison, N_ref = N_ref, N_total = .data$N_comparison + .data$N_ref ) %>% arrange(-1 * .data$eventN_total) # calculate stats for each row if (stat %in% c("RR", "Risk Ratio")) { aeCounts <- aeCounts %>% rowwise %>% mutate( result = fmsb::riskratio( X = .data$eventN_comparison, Y = .data$eventN_ref, m1 = .data$N_comparison, m2 = .data$N_ref ) %>% list, pvalue = .data$result$`p.value`, estimate = .data$result$estimate, ref_grp = settings$reference_group, comp_grp = settings$comparison_group ) %>% ungroup %>% select(-.data$result) %>% mutate(stat = "Risk Ratio") } else if (stat %in% c("RD", "Risk Difference")) { aeCounts <- aeCounts%>% rowwise %>% mutate( result = fmsb::riskdifference( a = .data$eventN_comparison, b = .data$eventN_ref, N1 = .data$N_comparison, N0 = .data$N_ref ) %>% list, pvalue = .data$result$`p.value`, estimate = .data$result$estimate, ref_grp = settings$reference_group, comp_grp = settings$comparison_group ) %>% ungroup %>% select(-.data$result) %>% mutate(stat = "Risk Difference") } else if (TRUE) { message("stat not supported yet :( ") } aeCounts<-aeCounts %>% mutate(logp = -log10(.data$pvalue)) %>% mutate( tooltip=paste0( 'Group: ', .data$strata, '<br/>', 'Risk Ratio: ', round(.data$estimate, 2), '<br/>', 'P Value: ', round(.data$pvalue, 2), '<br/>', .data$ref_grp, ': ', .data$eventN_ref, '/', .data$eventN_total, '<br/>', .data$comp_grp, ': ', .data$eventN_comparison, '/', .data$eventN_total, '<br/>' ) ) ## create one table from a list of tables return(aeCounts) }
/scratch/gouwar.j/cran-all/cranData/volcanoPlot/R/getStats.R
#' Volcano App #' #' Initializes stand-alone volcano plot shiny application. #' #' @param dfAE AE Data #' @param dfDemog demog data #' @param settings safetyGraphics settings #' @param runNow run app immediately? #' #' @return Initializes Shiny app. No return value. #' #' @import shiny #' #' @export volcanoApp <- function(dfAE=safetyData::adam_adae, dfDemog = safetyData::adam_adsl, settings=NULL,runNow=TRUE){ ## create default settings when settings is not defined by default if(is.null(settings)){ settings<-list( aes=list(id_col="USUBJID", bodsys_col="AEBODSYS", term_col = 'AEDECOD'), dm=list(id_col="USUBJID", treatment_col="ARM", "treatment_values"=list(group1="Placebo")) ) } ## create object containing data and setting to pass to server params <- reactive({ list( data=list(aes=dfAE, dm=dfDemog), settings=settings ) }) ## Create app with ui and server app <- shinyApp( ui = volcano_ui("vp"), server = function(input,output,session){ callModule(volcano_server, "vp", params) } ) if(runNow) runApp(app) else app }
/scratch/gouwar.j/cran-all/cranData/volcanoPlot/R/volcanoApp.R
#' Create a volcano plot #' #' Creates a paneled volcano plot showing the distribution of Adverse events. Options to highlight selected events and customize options are provided. #' #' @param data A data frame from getStats() #' @param highlights A list providing a column and values to be highlighted in the chart #' @param ... Extra options to change the look of the plot. `fillcol = #' c('sienna2', 'skyblue2', 'grey')`: fill colors; `pcutoff = 0.05`: p value #' cutoff; `ecutoff = 1`: estimate cutoff, `GroupLabels = c('Comparison #' Group', 'Reference Group')`: custom group labels. #' #' @return a volcano plot created with ggplot #' #' @examples #' settings<-list( #' stratification_col="AEBODSYS", #' group_col="ARM", #' reference_group="Placebo", #' comparison_group="Xanomeline High Dose", #' id_col="USUBJID" #' ) #' stats<-getStats(dfAE=safetyData::adam_adae, dfDemog = safetyData::adam_adsl, settings) #' volcanoPlot(stats) #' #' @import ggplot2 #' #' @export volcanoPlot <- function(data, highlights=c(), ...){ # process options for the plot opts <- list(...) if(!('fillcol' %in% names(opts))) { opts$fillcol = c('sienna2', 'skyblue2', 'grey')} if(!('pcutoff' %in% names(opts))) {opts$pcutoff = 0.05} if(!('ecutoff' %in% names(opts))) { opts$ecutoff <- ifelse(data$stat[1]=="Risk Difference",0,1) } # change fill color based on pvalue and estimate data$diffexp <- 'NO' data$diffexp[data$estimate >= opts$ecutoff & data$pvalue < opts$pcutoff] <- 'UP' data$diffexp[data$estimate < opts$ecutoff & data$pvalue < opts$pcutoff] <- 'DOWN' fillcolors <- c('DOWN' = opts$fillcol[1], 'UP' = opts$fillcol[2], 'NO' = opts$fillcol[3]) data$alpha <- 0.7 data$alpha[data$strata %in% highlights] <- 1 p<-ggplot(data, aes(.data$estimate,.data$logp)) + geom_point( aes( size = .data$eventN_total, fill = .data$diffexp, alpha = alpha ), pch = 21) + scale_size_continuous(range = c(2, 12)) + scale_fill_manual(values = fillcolors) + # adding cutoff lines geom_hline(yintercept = -log10(opts$pcutoff), color = 'grey30', linetype = "dashed") + geom_vline(xintercept = opts$ecutoff, color = 'grey30', linetype = "dashed") + # theming and labeling the plot theme_bw() + theme(legend.position = "none") + scale_x_continuous( expand = expansion(mult = c(0.05, 0.05)) ) + theme(aspect.ratio = 1) + # Facet on comparison facet_wrap(vars(.data$comp_grp)) return(p) }
/scratch/gouwar.j/cran-all/cranData/volcanoPlot/R/volcanoPlot.R
#' Volcano Plot Module - Server #' #' Modularized server for AE volcano plot. #' #' @param input module input #' @param output module output #' @param session module session #' @param params parameters object with `data` and `settings` options. #' #' @return returns shiny module Server function #' #' @import shiny #' @importFrom DT renderDT #' @importFrom purrr map #' @export volcano_server <- function(input, output, session, params) { ns <- session$ns cat('starting server') ## create a custom mapping for stats calculation mapping<-reactive({ dm<-params()$data$dm reference_group <- params()$settings$dm$treatment_values$group1 all_groups <- unique(dm[[params()$settings$dm$treatment_col]]) comparison_groups <- all_groups[all_groups != reference_group] mapping <- list( stratification_col=input$stratification_values, group_col=params()$settings$dm$treatment_col, reference_group=reference_group, comparison_group=comparison_groups, id_col=params()$settings$dm$id_col ) return(mapping) }) strata_cols <- reactive({ c( params()$settings$aes$bodsys_col, params()$settings$aes$term_col ) }) observe({ updateSelectizeInput( session, inputId = 'stratification_values', choices = strata_cols(), selected = strata_cols()[[1]] ) }) # calculate the stats stats<-reactive({ req(mapping()) stats <- mapping()$comparison_group %>% map(function(comp_group){ comp_mapping <- mapping() comp_mapping$comparison_group <- comp_group stats <- getStats( dfAE=params()$data$aes, dfDemog=params()$data$dm, settings=comp_mapping, stat=input$calculation_type ) return(stats) })%>% bind_rows }) ## Output plots output$volcanoPlot <- renderPlot({ volcanoPlot( data=stats(), highlights=selected_strata() ) }) # ############################################ # # Reactives for interactive brushing/hover # ############################################ #hover data hover_data <- reactive({ nearPoints( stats(), input$plot_hover, xvar="estimate", yvar="logp" ) }) #selected strata selected_strata <- reactive({ req(stats) unique(brushedPoints( stats(), input$plot_brush, xvar="estimate", yvar="logp" )$strata) }) #filtered ae data sub_aes <- reactive({ req(selected_strata()) raw_aes <- params()$data$aes sub_aes <- raw_aes %>% filter(.data[[mapping()$stratification_col]] %in% selected_strata()) }) #filtered comparison data sub_stat <- reactive({ req(selected_strata()) stats()[stats()$strata %in% selected_strata(),] }) ########################## # Linked table + Header ######################### output$footnote <- renderUI({ if( nrow(hover_data()) > 0 ){ HTML(paste(hover_data()$tooltip,collapse="<hr>")) }else{ 'Hover to see point details' } }) output$infoComp <- renderUI({ if( length(selected_strata()) == 1 ){ HTML(paste(nrow(sub_stat()),"comparisons from <strong>", selected_strata(),"</strong>")) }else if(length(selected_strata() > 1)){ HTML(paste(nrow(sub_stat()), "comparisons from <strong>", length(selected_strata()),"groups </strong>")) }else{ paste("Brush to see listings") } }) output$compListing <- renderDT({ req(sub_stat()) sub_stat() %>% select(-.data$tooltip) }) output$infoAE <- renderUI({ if( length(selected_strata()) == 1 ){ HTML(paste(nrow(sub_aes()),"AEs from <strong>", selected_strata(),"</strong>")) }else if(length(selected_strata() > 1)){ HTML(paste(nrow(sub_aes()), "AEs from <strong>", length(selected_strata()),"groups </strong>")) }else{ paste("Brush to see listings") } }) output$aeListing <- renderDT({ req(sub_aes()) sub_aes() }) }
/scratch/gouwar.j/cran-all/cranData/volcanoPlot/R/volcano_server.R
#' Volcano Plot Module - UI #' #' Modularized user interface for AE Volcano plot #' #' @param id module id #' #' @return returns shiny module UI #' #' @import shiny #' @importFrom DT DTOutput #' #' @export #' volcano_ui <- function(id) { ns <- NS(id) ## Show sidebar sidebar <- sidebarPanel( # Calculation type input selectizeInput( ns("calculation_type"), label="Measure of Association", choices = c( "Risk Ratio", "Risk Difference" ) ), # Stratification input selectizeInput( ns("stratification_values"), label="System Organ Glass / Preferred Term", choices = c() ) ) # show main panel with plots, data tables main <- mainPanel( plotOutput( ns("volcanoPlot"), height = "650px", hover = hoverOpts(ns("plot_hover"),delay=50), brush = brushOpts(ns("plot_brush"),resetOnNew = FALSE) ), tags$small(wellPanel(htmlOutput(ns("footnote")))), tabsetPanel(id=ns("tableWrap"), type = "tabs", tabPanel("Comparisons", div( h5(htmlOutput(ns("infoComp"))), DTOutput(ns("compListing"))) ), tabPanel("Adverse Events", div( h5(htmlOutput(ns("infoAE"))), DTOutput(ns("aeListing")) ) ) ) ) ## bring components together as complete ui ui <- fluidPage( sidebarLayout( sidebar, main, position = c("right"), fluid = TRUE ) ) return(ui) }
/scratch/gouwar.j/cran-all/cranData/volcanoPlot/R/volcano_ui.R
#' An R class to represent an H-polytope #' #' An H-polytope is a convex polytope defined by a set of linear inequalities or equivalently a \eqn{d}-dimensional H-polytope with \eqn{m} facets is defined by a \eqn{m\times d} matrix A and a \eqn{m}-dimensional vector b, s.t.: \eqn{Ax\leq b}. #' #' \describe{ #' \item{A}{An \eqn{m\times d} numerical matrix.} #' #' \item{b}{An \eqn{m}-dimensional vector b.} #' #' \item{volume}{The volume of the polytope if it is known, \eqn{NaN} otherwise by default.} #' #' \item{type}{A character with default value 'Hpolytope', to declare the representation of the polytope.} #' } #' #' @examples #' A = matrix(c(-1,0,0,-1,1,1), ncol=2, nrow=3, byrow=TRUE) #' b = c(0,0,1) #' P = Hpolytope(A = A, b = b) #' #' @name Hpolytope-class #' @rdname Hpolytope-class #' @exportClass Hpolytope Hpolytope <- setClass ( # Class name "Hpolytope", # Defining slot type representation ( A = "matrix", b = "numeric", volume = "numeric", type = "character" ), # Initializing slots prototype = list( A = as.matrix(0), b = as.numeric(NULL), volume = as.numeric(NaN), type = "Hpolytope" ) )
/scratch/gouwar.j/cran-all/cranData/volesti/R/HpolytopeClass.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' Construct a copula using uniform sampling from the unit simplex #' #' Given two families of parallel hyperplanes or a family of parallel hyperplanes and a family of concentric ellispoids centered at the origin intersecting the canonical simplex, this function uniformly samples from the canonical simplex and construct an approximation of the bivariate probability distribution, called copula (see \url{https://en.wikipedia.org/wiki/Copula_(probability_theory)}). #' At least two families of hyperplanes or one family of hyperplanes and one family of ellipsoids have to be given as input. #' #' @param r1 The \eqn{d}-dimensional normal vector of the first family of parallel hyperplanes. #' @param r2 Optional. The \eqn{d}-dimensional normal vector of the second family of parallel hyperplanes. #' @param sigma Optional. The \eqn{d\times d} symmetric positive semidefine matrix that describes the family of concentric ellipsoids centered at the origin. #' @param m The number of the slices for the copula. The default value is 100. #' @param n The number of points to sample. The default value is \eqn{5\cdot 10^5}. #' @param seed Optional. A fixed seed for the number generator. #' #' @references \cite{L. Cales, A. Chalkis, I.Z. Emiris, V. Fisikopoulos, #' \dQuote{Practical volume computation of structured convex bodies, and an application to modeling portfolio dependencies and financial crises,} \emph{Proc. of Symposium on Computational Geometry, Budapest, Hungary,} 2018.} #' #' @return A \eqn{m\times m} numerical matrix that corresponds to a copula. #' @examples #' # compute a copula for two random families of parallel hyperplanes #' h1 = runif(n = 10, min = 1, max = 1000) #' h1 = h1 / 1000 #' h2=runif(n = 10, min = 1, max = 1000) #' h2 = h2 / 1000 #' cop = copula(r1 = h1, r2 = h2, m = 10, n = 100000) #' #' # compute a copula for a family of parallel hyperplanes and a family of conentric ellipsoids #' h = runif(n = 10, min = 1, max = 1000) #' h = h / 1000 #' E = replicate(10, rnorm(20)) #' E = cov(E) #' cop = copula(r1 = h, sigma = E, m = 10, n = 100000) #' #' @export copula <- function(r1, r2 = NULL, sigma = NULL, m = NULL, n = NULL, seed = NULL) { .Call(`_volesti_copula`, r1, r2, sigma, m, n, seed) } #' Sample perfect uniformly distributed points from well known convex bodies: (a) the unit simplex, (b) the canonical simplex, (c) the boundary of a hypersphere or (d) the interior of a hypersphere. #' #' The \eqn{d}-dimensional unit simplex is the set of points \eqn{\vec{x}\in \R^d}, s.t.: \eqn{\sum_i x_i\leq 1}, \eqn{x_i\geq 0}. The \eqn{d}-dimensional canonical simplex is the set of points \eqn{\vec{x}\in \R^d}, s.t.: \eqn{\sum_i x_i = 1}, \eqn{x_i\geq 0}. #' #' @param body A list to request exact uniform sampling from special well known convex bodies through the following input parameters: #' \itemize{ #' \item{\code{type} }{ A string that declares the type of the body for the exact sampling: a) \code{'unit_simplex'} for the unit simplex, b) \code{'canonical_simplex'} for the canonical simplex, c) \code{'hypersphere'} for the boundary of a hypersphere centered at the origin, d) \code{'ball'} for the interior of a hypersphere centered at the origin.} #' \item{\code{dimension} }{ An integer that declares the dimension when exact sampling is enabled for a simplex or a hypersphere.} #' \item{\code{radius} }{ The radius of the \eqn{d}-dimensional hypersphere. The default value is \eqn{1}.} #' \item{\code{seed} }{ A fixed seed for the number generator.} #' } #' @param n The number of points that the function is going to sample. #' #' @references \cite{R.Y. Rubinstein and B. Melamed, #' \dQuote{Modern simulation and modeling} \emph{ Wiley Series in Probability and Statistics,} 1998.} #' @references \cite{A Smith, Noah and W Tromble, Roy, #' \dQuote{Sampling Uniformly from the Unit Simplex,} \emph{ Center for Language and Speech Processing Johns Hopkins University,} 2004.} #' #' @return A \eqn{d\times n} matrix that contains, column-wise, the sampled points from the convex polytope P. #' @examples #' # 100 uniform points from the 2-d unit ball #' points = direct_sampling(n = 100, body = list("type" = "ball", "dimension" = 2)) #' @export direct_sampling <- function(body, n) { .Call(`_volesti_direct_sampling`, body, n) } #' Compute the exact volume of (a) a zonotope (b) an arbitrary simplex in V-representation or (c) if the volume is known and declared by the input object. #' #' Given a zonotope (as an object of class Zonotope), this function computes the sum of the absolute values of the determinants of all the \eqn{d \times d} submatrices of the \eqn{m\times d} matrix \eqn{G} that contains row-wise the \eqn{m} \eqn{d}-dimensional segments that define the zonotope. #' For an arbitrary simplex that is given in V-representation this function computes the absolute value of the determinant formed by the simplex's points assuming it is shifted to the origin. #' #' @param P A polytope #' #' @references \cite{E. Gover and N. Krikorian, #' \dQuote{Determinants and the Volumes of Parallelotopes and Zonotopes,} \emph{Linear Algebra and its Applications, 433(1), 28 - 40,} 2010.} #' #' @return The exact volume of the input polytope, for zonotopes, simplices in V-representation and polytopes with known exact volume #' @examples #' #' # compute the exact volume of a 5-dimensional zonotope defined by the Minkowski sum of 10 segments #' Z = gen_rand_zonotope(2, 5) #' vol = exact_vol(Z) #' #' \donttest{# compute the exact volume of a 2-d arbitrary simplex #' V = matrix(c(2,3,-1,7,0,0),ncol = 2, nrow = 3, byrow = TRUE) #' P = Vpolytope(V = V) #' vol = exact_vol(P) #' } #' #' # compute the exact volume the 10-dimensional cross polytope #' P = gen_cross(10,'V') #' vol = exact_vol(P) #' @export exact_vol <- function(P) { .Call(`_volesti_exact_vol`, P) } #' Compute the percentage of the volume of the simplex that is contained in the intersection of a half-space and the simplex. #' #' A half-space \eqn{H} is given as a pair of a vector \eqn{a\in R^d} and a scalar \eqn{z0\in R} s.t.: \eqn{a^Tx\leq z0}. This function calls the Ali's version of the Varsi formula to compute a frustum of the simplex. #' #' @param a A \eqn{d}-dimensional vector that defines the direction of the hyperplane. #' @param z0 The scalar that defines the half-space. #' #' @references \cite{Varsi, Giulio, #' \dQuote{The multidimensional content of the frustum of the simplex,} \emph{Pacific J. Math. 46, no. 1, 303--314,} 1973.} #' #' @references \cite{Ali, Mir M., #' \dQuote{Content of the frustum of a simplex,} \emph{ Pacific J. Math. 48, no. 2, 313--322,} 1973.} #' #' @return The percentage of the volume of the simplex that is contained in the intersection of a given half-space and the simplex. #' #' @examples #' # compute the frustum of H: -x1+x2<=0 #' a=c(-1,1) #' z0=0 #' frustum = frustum_of_simplex(a, z0) #' @export frustum_of_simplex <- function(a, z0) { .Call(`_volesti_frustum_of_simplex`, a, z0) } #' Compute an inscribed ball of a convex polytope #' #' For a H-polytope described by a \eqn{m\times d} matrix \eqn{A} and a \eqn{m}-dimensional vector \eqn{b}, s.t.: \eqn{P=\{x\ |\ Ax\leq b\} }, this function computes the largest inscribed ball (Chebychev ball) by solving the corresponding linear program. #' For both zonotopes and V-polytopes the function computes the minimum \eqn{r} s.t.: \eqn{ r e_i \in P} for all \eqn{i=1, \dots ,d}. Then the ball centered at the origin with radius \eqn{r/ \sqrt{d}} is an inscribed ball. #' #' @param P A convex polytope. It is an object from class (a) Hpolytope or (b) Vpolytope or (c) Zonotope or (d) VpolytopeIntersection. #' #' @return A \eqn{(d+1)}-dimensional vector that describes the inscribed ball. The first \eqn{d} coordinates corresponds to the center of the ball and the last one to the radius. #' #' @examples #' # compute the Chebychev ball of the 2d unit simplex #' P = gen_simplex(2,'H') #' ball_vec = inner_ball(P) #' #' # compute an inscribed ball of the 3-dimensional unit cube in V-representation #' P = gen_cube(3, 'V') #' ball_vec = inner_ball(P) #' @export inner_ball <- function(P) { .Call(`_volesti_inner_ball`, P) } #' An internal Rccp function to read a SDPA format file #' #' @param input_file Name of the input file #' #' @keywords internal #' #' @return A list with two named items: an item "matrices" which is a list of the matrices and an vector "objFunction" load_sdpa_format_file <- function(input_file = NULL) { .Call(`_volesti_load_sdpa_format_file`, input_file) } #' An internal Rccp function as a polytope generator #' #' @param kind_gen An integer to declare the type of the polytope. #' @param Vpoly_gen A boolean parameter to declare if the requested polytope has to be in V-representation. #' @param Zono_gen A boolean parameter to declare if the requested polytope has to be a zonotope. #' @param dim_gen An integer to declare the dimension of the requested polytope. #' @param m_gen An integer to declare the number of generators for the requested random zonotope or the number of vertices for a V-polytope. #' @param seed Optional. A fixed seed for the random polytope generator. #' #' @keywords internal #' #' @return A numerical matrix describing the requested polytope poly_gen <- function(kind_gen, Vpoly_gen, Zono_gen, dim_gen, m_gen, seed = NULL) { .Call(`_volesti_poly_gen`, kind_gen, Vpoly_gen, Zono_gen, dim_gen, m_gen, seed) } #' An internal Rccp function for the random rotation of a convex polytope #' #' @param P A convex polytope (H-, V-polytope or a zonotope). #' @param T Optional. A rotation matrix. #' @param seed Optional. A fixed seed for the random linear map generator. #' #' @keywords internal #' #' @return A matrix that describes the rotated polytope rotating <- function(P, T = NULL, seed = NULL) { .Call(`_volesti_rotating`, P, T, seed) } #' Internal rcpp function for the rounding of a convex polytope #' #' @param P A convex polytope (H- or V-representation or zonotope). #' @param settings A list to set the random walk and its walk length #' @param seed Optional. A fixed seed for the number generator. #' #' @keywords internal #' #' @return A numerical matrix that describes the rounded polytope, a numerical matrix of the inverse linear transofmation that is applied on the input polytope, the numerical vector the the input polytope is shifted and the determinant of the matrix of the linear transformation that is applied on the input polytope. rounding <- function(P, settings = NULL, seed = NULL) { .Call(`_volesti_rounding`, P, settings, seed) } #' Sample uniformly or normally distributed points from a convex Polytope (H-polytope, V-polytope, zonotope or intersection of two V-polytopes). #' #' Sample n points with uniform or multidimensional spherical gaussian -with a mode at any point- as the target distribution. #' #' @param P A convex polytope. It is an object from class (a) Hpolytope or (b) Vpolytope or (c) Zonotope or (d) VpolytopeIntersection. #' @param n The number of points that the function is going to sample from the convex polytope. #' @param random_walk Optional. A list that declares the random walk and some related parameters as follows: #' \itemize{ #' \item{\code{walk} }{ A string to declare the random walk: i) \code{'CDHR'} for Coordinate Directions Hit-and-Run, ii) \code{'RDHR'} for Random Directions Hit-and-Run, iii) \code{'BaW'} for Ball Walk, iv) \code{'BiW'} for Billiard walk, v) \code{'BCDHR'} boundary sampling by keeping the extreme points of CDHR or vi) \code{'BRDHR'} boundary sampling by keeping the extreme points of RDHR. The default walk is \code{'BiW'} for the uniform distribution or \code{'CDHR'} for the Gaussian distribution.} #' \item{\code{walk_length} }{ The number of the steps per generated point for the random walk. The default value is 1.} #' \item{\code{nburns} }{ The number of points to burn before start sampling.} #' \item{\code{starting_point} }{ A \eqn{d}-dimensional numerical vector that declares a starting point in the interior of the polytope for the random walk. The default choice is the center of the ball as that one computed by the function \code{inner_ball()}.} #' \item{\code{BaW_rad} }{ The radius for the ball walk.} #' \item{\code{L} }{ The maximum length of the billiard trajectory.} #' \item{\code{seed} }{ A fixed seed for the number generator.} #' } #' @param distribution Optional. A list that declares the target density and some related parameters as follows: #' \itemize{ #' \item{\code{density} }{ A string: (a) \code{'uniform'} for the uniform distribution or b) \code{'gaussian'} for the multidimensional spherical distribution. The default target distribution is uniform.} #' \item{\code{variance} }{ The variance of the multidimensional spherical gaussian. The default value is 1.} #' \item{\code{mode} }{ A \eqn{d}-dimensional numerical vector that declares the mode of the Gaussian distribution. The default choice is the center of the as that one computed by the function \code{inner_ball()}.} #' } #' #' @return A \eqn{d\times n} matrix that contains, column-wise, the sampled points from the convex polytope P. #' @examples #' # uniform distribution from the 3d unit cube in H-representation using ball walk #' P = gen_cube(3, 'H') #' points = sample_points(P, n = 100, random_walk = list("walk" = "BaW", "walk_length" = 5)) #' #' # gaussian distribution from the 2d unit simplex in H-representation with variance = 2 #' A = matrix(c(-1,0,0,-1,1,1), ncol=2, nrow=3, byrow=TRUE) #' b = c(0,0,1) #' P = Hpolytope(A = A, b = b) #' points = sample_points(P, n = 100, distribution = list("density" = "gaussian", "variance" = 2)) #' #' # uniform points from the boundary of a 2-dimensional random H-polytope #' P = gen_rand_hpoly(2,20) #' points = sample_points(P, n = 100, random_walk = list("walk" = "BRDHR")) #' #' @export sample_points <- function(P, n, random_walk = NULL, distribution = NULL) { .Call(`_volesti_sample_points`, P, n, random_walk, distribution) } #' The main function for volume approximation of a convex Polytope (H-polytope, V-polytope, zonotope or intersection of two V-polytopes) #' #' For the volume approximation can be used three algorithms. Either CoolingBodies (CB) or SequenceOfBalls (SOB) or CoolingGaussian (CG). An H-polytope with \eqn{m} facets is described by a \eqn{m\times d} matrix \eqn{A} and a \eqn{m}-dimensional vector \eqn{b}, s.t.: \eqn{P=\{x\ |\ Ax\leq b\} }. A V-polytope is defined as the convex hull of \eqn{m} \eqn{d}-dimensional points which correspond to the vertices of P. A zonotope is desrcibed by the Minkowski sum of \eqn{m} \eqn{d}-dimensional segments. #' #' @param P A convex polytope. It is an object from class a) Hpolytope or b) Vpolytope or c) Zonotope or d) VpolytopeIntersection. #' @param settings Optional. A list that declares which algorithm, random walk and values of parameters to use, as follows: #' \itemize{ #' \item{\code{algorithm} }{ A string to set the algorithm to use: a) \code{'CB'} for CB algorithm, b) \code{'SoB'} for SOB algorithm or b) \code{'CG'} for CG algorithm. The defalut algorithm is \code{'CB'}.} #' \item{\code{error} }{ A numeric value to set the upper bound for the approximation error. The default value is \eqn{1} for SOB algorithm and \eqn{0.1} otherwise.} #' \item{\code{random_walk} }{ A string that declares the random walk method: a) \code{'CDHR'} for Coordinate Directions Hit-and-Run, b) \code{'RDHR'} for Random Directions Hit-and-Run, c) \code{'BaW'} for Ball Walk, or \code{'BiW'} for Billiard walk. For CB and SOB algorithms the default walk is \code{'CDHR'} for H-polytopes and \code{'BiW'} for the other representations. For CG algorithm the default walk is \code{'CDHR'} for H-polytopes and \code{'RDHR'} for the other representations.} #' \item{\code{walk_length} }{ An integer to set the number of the steps for the random walk. The default value is \eqn{\lfloor 10 + d/10\rfloor} for \code{'SOB'} and \eqn{1} otherwise.} #' \item{\code{win_len} }{ The length of the sliding window for CB or CG algorithm. The default value is \eqn{400+3d^2} for CB or \eqn{500+4d^2} for CG.} #' \item{\code{hpoly} }{ A boolean parameter to use H-polytopes in MMC of CB algorithm when the input polytope is a zonotope. The default value is \code{TRUE} when the order of the zonotope is \eqn{<5}, otherwise it is \code{FALSE}.} #' \item{\code{seed} }{ A fixed seed for the number generator.} #' } #' @param rounding A boolean parameter for rounding. The default value is \code{FALSE}. #' #' @references \cite{I.Z.Emiris and V. Fisikopoulos, #' \dQuote{Practical polytope volume approximation,} \emph{ACM Trans. Math. Soft.,} 2018.}, #' @references \cite{A. Chalkis and I.Z.Emiris and V. Fisikopoulos, #' \dQuote{Practical Volume Estimation by a New Annealing Schedule for Cooling Convex Bodies,} \emph{CoRR, abs/1905.05494,} 2019.}, #' @references \cite{B. Cousins and S. Vempala, \dQuote{A practical volume algorithm,} \emph{Springer-Verlag Berlin Heidelberg and The Mathematical Programming Society,} 2015.} #' #' #' @return The approximation of the volume of a convex polytope. #' @examples #' #' # calling SOB algorithm for a H-polytope (3d unit simplex) #' HP = gen_cube(3,'H') #' vol = volume(HP) #' #' # calling CG algorithm for a V-polytope (2d simplex) #' VP = gen_simplex(2,'V') #' vol = volume(VP, settings = list("algorithm" = "CG")) #' #' # calling CG algorithm for a 2-dimensional zonotope defined as the Minkowski sum of 4 segments #' Z = gen_rand_zonotope(2, 4) #' vol = volume(Z, settings = list("random_walk" = "RDHR", "walk_length" = 2)) #' #' @export volume <- function(P, settings = NULL, rounding = FALSE) { .Call(`_volesti_volume`, P, settings, rounding) } #' Write a SDPA format file #' #' Outputs a spectrahedron (the matrices defining a linear matrix inequality) and a vector (the objective function) #' to a SDPA format file. #' #' @param spectrahedron A spectrahedron in n dimensions; must be an object of class Spectrahedron #' @param objective_function A numerical vector of length n #' @param output_file Name of the output file #' #' @examples #' \donttest{ #' A0 = matrix(c(-1,0,0,0,-2,1,0,1,-2), nrow=3, ncol=3, byrow = TRUE) #' A1 = matrix(c(-1,0,0,0,0,1,0,1,0), nrow=3, ncol=3, byrow = TRUE) #' A2 = matrix(c(0,0,-1,0,0,0,-1,0,0), nrow=3, ncol=3, byrow = TRUE) #' lmi = list(A0, A1, A2) #' S = Spectrahedron(matrices = lmi) #' objFunction = c(1,1) #' write_sdpa_format_file(S, objFunction, "output.txt") #' } #' @export write_sdpa_format_file <- function(spectrahedron, objective_function, output_file) { invisible(.Call(`_volesti_write_sdpa_format_file`, spectrahedron, objective_function, output_file)) } #' An internal Rccp function for the over-approximation of a zonotope #' #' @param Z A zonotope. #' @param fit_ratio Optional. A boolean parameter to request the computation of the ratio of fitness. #' @param settings Optional. A list that declares the values of the parameters of CB algorithm. #' @param seed Optional. A fixed seed for the number generator. #' #' @keywords internal #' #' @return A List that contains a numerical matrix that describes the PCA approximation as a H-polytope and the ratio of fitness. zono_approx <- function(Z, fit_ratio = NULL, settings = NULL, seed = NULL) { .Call(`_volesti_zono_approx`, Z, fit_ratio, settings, seed) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/RcppExports.R
#' An R class to represent a Spectrahedron #' #' A spectrahedron is a convex body defined by a linear matrix inequality of the form \eqn{A_0 + x_1 A_1 + ... + x_n A_n \preceq 0}. #' The matrices \eqn{A_i} are symmetric \eqn{m \times m} real matrices and \eqn{\preceq 0} denoted negative semidefiniteness. #' #' \describe{ #' \item{matrices}{A List that contains the matrices \eqn{A_0, A_1, ..., A_n}.} #' } #' #' @examples #' A0 = matrix(c(-1,0,0,0,-2,1,0,1,-2), nrow=3, ncol=3, byrow = TRUE) #' A1 = matrix(c(-1,0,0,0,0,1,0,1,0), nrow=3, ncol=3, byrow = TRUE) #' A2 = matrix(c(0,0,-1,0,0,0,-1,0,0), nrow=3, ncol=3, byrow = TRUE) #' lmi = list(A0, A1, A2) #' S = Spectrahedron(matrices = lmi); #' #' @name Spectrahedron-class #' @rdname Spectrahedron-class #' @exportClass Spectrahedron Spectrahedron <- setClass ( # Class name "Spectrahedron", # Defining slot type representation ( matrices = "list" ), # Initializing slots prototype = list( matrices = list() ) )
/scratch/gouwar.j/cran-all/cranData/volesti/R/SpectrahedronClass.R
#' An R class to represent a V-polytope #' #' A V-polytope is a convex polytope defined by the set of its vertices. #' #' \describe{ #' \item{V}{An \eqn{m\times d} numerical matrix that contains the vertices row-wise.} #' #' \item{volume}{The volume of the polytope if it is known, \eqn{NaN} otherwise by default.} #' #' \item{type}{A character with default value 'Vpolytope', to declare the representation of the polytope.} #' } #' #' @examples #' V = matrix(c(2,3,-1,7,0,0),ncol = 2, nrow = 3, byrow = TRUE) #' P = Vpolytope(V = V) #' #' @name Vpolytope-class #' @rdname Vpolytope-class #' @exportClass Vpolytope Vpolytope <- setClass ( # Class name "Vpolytope", # Defining slot type representation ( V = "matrix", volume = "numeric", type = "character" ), # Initializing slots prototype = list( V = as.matrix(0), volume = as.numeric(NaN), type = "Vpolytope" ) )
/scratch/gouwar.j/cran-all/cranData/volesti/R/VpolytopeClass.R
#' An R class to represent the intersection of two V-polytopes #' #' An intersection of two V-polytopes is defined by the intersection of the two coresponding convex hulls. #' #' \describe{ #' \item{V1}{An \eqn{m\times d} numerical matrix that contains the vertices of the first V-polytope (row-wise).} #' #' \item{V2}{An \eqn{q\times d} numerical matrix that contains the vertices of the second V-polytope (row-wise).} #' #' \item{volume}{The volume of the polytope if it is known, \eqn{NaN} otherwise by default.} #' #' \item{type}{A character with default value 'VpolytopeIntersection', to declare the representation of the polytope.} #' } #' #' @examples #' P1 = gen_simplex(2,'V') #' P2 = gen_cross(2,'V') #' P = VpolytopeIntersection(V1 = P1@V, V2 = P2@V) #' #' @name VpolytopeIntersection-class #' @rdname VpolytopeIntersection-class #' @exportClass VpolytopeIntersection VpolytopeIntersection <- setClass ( # Class name "VpolytopeIntersection", # Defining slot type representation ( V1 = "matrix", V2 = "matrix", volume = "numeric", type = "character" ), # Initializing slots prototype = list( V1 = as.matrix(0), V2 = as.matrix(0), volume = as.numeric(NaN), type = "VpolytopeIntersection" ) )
/scratch/gouwar.j/cran-all/cranData/volesti/R/VpolytopeIntersectionClass.R
#' An R class to represent a Zonotope #' #' A zonotope is a convex polytope defined by the Minkowski sum of \eqn{m} \eqn{d}-dimensional segments. #' #' \describe{ #' \item{G}{An \eqn{m\times d} numerical matrix that contains the segments (or generators) row-wise} #' #' \item{volume}{The volume of the polytope if it is known, \eqn{NaN} otherwise by default.} #' #' \item{type}{A character with default value 'Zonotope', to declare the representation of the polytope.} #' } #' #' @examples #' G = matrix(c(2,3,-1,7,0,0),ncol = 2, nrow = 3, byrow = TRUE) #' P = Zonotope(G = G) #' #' @name Zonotope-class #' @rdname Zonotope-class #' @exportClass Zonotope Zonotope <- setClass ( # Class name "Zonotope", # Defining slot type representation ( G = "matrix", volume = "numeric", type = "character" ), # Initializing slots prototype = list( G = as.matrix(0), volume = as.numeric(NaN), type = "Zonotope" ) )
/scratch/gouwar.j/cran-all/cranData/volesti/R/ZonotopeClass.R
#' Compute an indicator for each time period that describes the state of a market. #' #' Given a matrix that contains row-wise the assets' returns and a sliding window \code{win_length}, this function computes an approximation of the joint distribution (copula, e.g. see \url{https://en.wikipedia.org/wiki/Copula_(probability_theory)}) between portfolios' return and volatility in each time period defined by \code{win_len}. #' For each copula it computes an indicator: If the indicator is large it corresponds to a crisis period and if it is small it corresponds to a normal period. #' In particular, the periods over which the indicator is greater than 1 for more than 60 consecutive sliding windows are warnings and for more than 100 are crisis. The sliding window is shifted by one day. #' #' @param returns A \eqn{d}-dimensional vector that describes the direction of the first family of parallel hyperplanes. #' @param parameters A list to set a parameterization. #' \itemize{ #' \item{win_length }{ The length of the sliding window. The default value is 60.} #' \item{m } { The number of slices for the copula. The default value is 100.} #' \item{n }{ The number of points to sample. The default value is \eqn{5\cdot 10^5}.} #' \item{nwarning }{ The number of consecutive indicators larger than 1 required to declare a warning period. The default value is 60.} #' \item{ncrisis }{ The number of consecutive indicators larger than 1 required to declare a crisis period. The default value is 100.} #' \item{seed }{ A fixed seed for the number generator.} #' } #' #' @references \cite{L. Cales, A. Chalkis, I.Z. Emiris, V. Fisikopoulos, #' \dQuote{Practical volume computation of structured convex bodies, and an application to modeling portfolio dependencies and financial crises,} \emph{Proc. of Symposium on Computational Geometry, Budapest, Hungary,} 2018.} #' #' @return A list that contains the indicators and the corresponding vector that label each time period with respect to the market state: a) normal, b) crisis, c) warning. #' #' @examples #' # simple example on random asset returns #' asset_returns = replicate(10, rnorm(14)) #' market_states_and_indicators = compute_indicators(asset_returns, #' parameters = list("win_length" = 10, "m" = 10, "n" = 10000, "nwarning" = 2, "ncrisis" = 3)) #' #' @export #' @useDynLib volesti, .registration=TRUE #' @importFrom Rcpp evalCpp #' @importFrom Rcpp loadModule #' @importFrom "utils" "read.csv" #' @importFrom "stats" "cov" #' @importFrom "methods" "new" compute_indicators <- function(returns, parameters = list("win_length" = 60, "m" = 100, "n" = 500000, "nwarning" = 60, "ncrisis" = 100)) { win_length = 60 if (!is.null(parameters$win_length)) { win_length = parameters$win_length } m=100 if (!is.null(parameters$m)){ m = parameters$m } n = 500000 if (!is.null(parameters$n)){ n = parameters$n } nwarning = 60 if (!is.null(parameters$nwarning)) { nwarning = parameters$nwarning } ncrisis = 100 if (!is.null(parameters$ncrisis)) { ncrisis = parameters$ncrisis } seed = NULL if (!is.null(parameters$seed)) { seed = parameters$seed } nrows = dim(returns)[1] nassets = dim(returns)[2] wl = win_length-1 indicators = c() for (i in 1:(nrows-wl)) { Win=i:(i+wl) E = cov(returns[Win,]) compRet = rep(1,nassets) for (j in 1:nassets) { for (k in Win) { compRet[j] = compRet[j] * (1 + returns[k, j]) } compRet[j] = compRet[j] - 1 } cop = copula(r1 = compRet, sigma = E, m = m, n = n, seed = seed) blue_mass = 0 red_mass = 0 for (row in 1:m) { for (col in 1:m) { if (row-col<=0.2*m && row-col>=-0.2*m) { if (row+col<0.8*m || row+col>1.2*m) { red_mass = red_mass + cop[row,col] } } else { if (row+col>=0.8*m+1 && row+col<=1.2*m+1) { blue_mass = blue_mass + cop[row,col] } } } } indicators = c(indicators, blue_mass / red_mass) } N = length(indicators) index = 0 set_index = FALSE col = rep("normal", N) for (i in 1:N) { if(indicators[i]>1 && !set_index){ index = i set_index = TRUE } else if (indicators[i]<1) { if(set_index){ if(i-index > nwarning-1 && i-index <= ncrisis-1){ col[index:(i-1)] = "warning" } else if(i-index > ncrisis-1) { col[index:(i-1)] = "crisis" } } set_index = FALSE } } if(set_index){ if(N-index+1 > nwarning-1 && N-index+1 <= ncrisis-1){ col[index:i] = "warning" } else if(N-index+1 > ncrisis-1) { col[index:i] = "crisis" } } return(list("indicators" = indicators, market_states = col)) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/compute_indicators.R
#' Generator function for cross polytopes #' #' This function generates the \eqn{d}-dimensional cross polytope in H- or V-representation. #' #' @param dimension The dimension of the cross polytope. #' @param representation A string to declare the representation. It has to be \code{'H'} for H-representation or \code{'V'} for V-representation. Default valus is 'H'. #' #' @return A polytope class representing a cross polytope in H- or V-representation. #' @examples #' # generate a 10-dimensional cross polytope in H-representation #' P = gen_cross(5, 'H') #' #' # generate a 15-dimension cross polytope in V-representation #' P = gen_cross(15, 'V') #' @export gen_cross <- function(dimension, representation = 'H') { kind_gen = 2 m_gen = 0 if (representation == 'V') { Vpoly_gen = TRUE } else if (representation == 'H') { Vpoly_gen = FALSE } else { stop('Not a known representation.') } Mat = poly_gen(kind_gen, Vpoly_gen, FALSE, dimension, m_gen) # first column is the vector b b = Mat[, 1] Mat = Mat[, -c(1), drop = FALSE] if (Vpoly_gen) { P = Vpolytope(V = Mat, volume = 2^dimension / prod(1:dimension)) } else { P = Hpolytope(A = -Mat, b = b, volume = 2^dimension / prod(1:dimension)) } return(P) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/gen_cross.R
#' Generator function for hypercubes #' #' This function generates the \eqn{d}-dimensional unit hypercube \eqn{[-1,1]^d} in H- or V-representation. #' #' @param dimension The dimension of the hypercube #' @param representation A string to declare the representation. It has to be \code{'H'} for H-representation or \code{'V'} for V-representation. Default valus is 'H'. #' #' @return A polytope class representing the unit \eqn{d}-dimensional hypercube in H- or V-representation. #' @examples #' # generate a 10-dimensional hypercube in H-representation #' P = gen_cube(10, 'H') #' #' # generate a 15-dimension hypercube in V-representation #' P = gen_cube(5, 'V') #' @export gen_cube <- function(dimension, representation = 'H') { kind_gen = 1 m_gen = 0 if (representation == 'V') { Vpoly_gen = TRUE } else if (representation == 'H') { Vpoly_gen = FALSE } else { stop('Not a known representation.') } Mat = poly_gen(kind_gen, Vpoly_gen, FALSE, dimension, m_gen) # first column is the vector b b = Mat[, 1] Mat = Mat[, -c(1), drop = FALSE] if (Vpoly_gen) { P = Vpolytope(V = Mat, volume = 2^dimension) } else { P = Hpolytope(A = -Mat, b = b, volume = 2^dimension) } return(P) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/gen_cube.R
#' Generator function for product of simplices #' #' This function generates a \eqn{2d}-dimensional polytope that is defined as the product of two \eqn{d}-dimensional unit simplices in H-representation. #' #' @param dimension The dimension of the simplices. #' #' @return A polytope class representing the product of the two \eqn{d}-dimensional unit simplices in H-representation. #' #' @examples #' # generate a product of two 5-dimensional simplices. #' P = gen_prod_simplex(5) #' @export gen_prod_simplex <- function(dimension) { kind_gen = 4 m_gen = 0 Vpoly_gen = FALSE Mat = poly_gen(kind_gen, Vpoly_gen, FALSE, dimension, m_gen) # first column is the vector b b = Mat[, 1] Mat = Mat[, -c(1), drop = FALSE] P = Hpolytope(A = -Mat, b = b, volume = (1/prod(1:dimension))^2) return(P) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/gen_prod_simplex.R
#' Generator function for random H-polytopes #' #' This function generates a \eqn{d}-dimensional polytope in H-representation with \eqn{m} facets. We pick \eqn{m} random hyperplanes tangent on the \eqn{d}-dimensional unit hypersphere as facets. #' #' @param dimension The dimension of the convex polytope. #' @param nfacets The number of the facets. #' @param generator A list that could contain two elements. #' \itemize{ #' \item{constants }{ To declare how to set the constants \eqn{b_i} for each facets: (i) 'sphere', each hyperplane is tangent to the hypersphere of radius 10, (ii) 'uniform' for each \eqn{b_i} the generator picks a uniform number from \eqn{(0,1)}. The defalut value is 'sphere'.} #' \item{seed }{ Optional. A fixed seed for the number generator.} #' } #' #' @return A polytope class representing a H-polytope. #' @examples #' # generate a 10-dimensional polytope with 50 facets #' P = gen_rand_hpoly(10, 50) #' @export gen_rand_hpoly <- function(dimension, nfacets, generator = list('constants' = 'sphere')) { seed = NULL if (!is.null(generator$seed)) { seed = generator$seed } if (is.null(generator$constants)) { kind_gen = 6 } else if (generator$constants == 'sphere'){ kind_gen = 6 } else if (generator$constants == 'uniform') { kind_gen = 7 } else { stop("Wrong generator!") } Vpoly_gen = FALSE Mat = poly_gen(kind_gen, Vpoly_gen, FALSE, dimension, nfacets, seed) # first column is the vector b b = Mat[, 1] Mat = Mat[, -c(1), drop = FALSE] P = Hpolytope(A = Mat, b = b) return(P) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/gen_rand_hpoly.R
#' Generator function for random V-polytopes #' #' This function generates a \eqn{d}-dimensional polytope in V-representation with \eqn{m} vertices. We pick \eqn{m} random points from the boundary of the \eqn{d}-dimensional unit hypersphere as vertices. #' #' @param dimension The dimension of the convex polytope. #' @param nvertices The number of the vertices. #' @param generator A list that could contain two elements. #' \itemize{ #' \item{body }{ the body that the generator samples uniformly the vertices from: (i) 'cube' or (ii) 'sphere', the default value is 'sphere'.} #' \item{seed }{ Optional. A fixed seed for the number generator.} #' } #' #' @return A polytope class representing a V-polytope. #' @examples #' # generate a 10-dimensional polytope defined as the convex hull of 25 random vertices #' P = gen_rand_vpoly(10, 25) #' @export gen_rand_vpoly <- function(dimension, nvertices, generator = list('body' = 'sphere')) { seed = NULL if (!is.null(generator$seed)) { seed = generator$seed } if (is.null(generator$body)) { kind_gen = 4 } else if (generator$body == 'cube'){ kind_gen = 5 } else if (generator$body == 'sphere') { kind_gen = 4 } else { stop("Wrong generator!") } Mat = poly_gen(kind_gen, TRUE, FALSE, dimension, nvertices, seed) # first column is the vector b b = Mat[, 1] Mat = Mat[, -c(1), drop = FALSE] P = Vpolytope(V = Mat) return(P) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/gen_rand_vpoly.R
#' Generator function for zonotopes #' #' This function generates a random \eqn{d}-dimensional zonotope defined by the Minkowski sum of \eqn{m} \eqn{d}-dimensional segments. #' The function considers \eqn{m} random directions in \eqn{R^d}. There are three strategies to pick the length of each segment: a) it is uniformly sampled from \eqn{[0,100]}, b) it is random from \eqn{\mathcal{N}(50,(50/3)^2)} truncated to \eqn{[0,100]}, c) it is random from \eqn{Exp(1/30)} truncated to \eqn{[0,100]}. #' #' @param dimension The dimension of the zonotope. #' @param nsegments The number of segments that generate the zonotope. #' @param generator A list that could contain two elements. #' \itemize{ #' \item{distribution }{ the distribution to pick the length of each segment from \eqn{[0,100]}: (i) 'uniform', (ii) 'gaussian' or (iii) 'exponential', the default value is 'uniform.} #' \item {seed }{ Optional. A fixed seed for the number generator.} #' } #' #' @return A polytope class representing a zonotope. #' #' @examples #' # generate a 10-dimensional zonotope defined by the Minkowski sum of 20 segments #' P = gen_rand_zonotope(10, 20) #' @export gen_rand_zonotope <- function(dimension, nsegments, generator = list('distribution' = 'uniform')) { seed = NULL if (!is.null(generator$seed)) { seed = generator$seed } if (is.null(generator$distribution)) { kind_gen = 1 } else if (generator$distribution == 'gaussian') { kind_gen = 2 } else if (generator$distribution == 'exponential') { kind_gen = 3 } else if (generator$distribution == 'uniform'){ kind_gen = 1 } else { stop("Wrong generator!") } Mat = poly_gen(kind_gen, FALSE, TRUE, dimension, nsegments, seed) # first column is the vector b b = Mat[, 1] Mat = Mat[, -c(1), drop = FALSE] P = Zonotope(G = Mat) return(P) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/gen_rand_zonotope.R
#' Generator function for simplices #' #' This function generates the \eqn{d}-dimensional unit simplex in H- or V-representation. #' #' @param dimension The dimension of the unit simplex. #' @param representation A string to declare the representation. It has to be \code{'H'} for H-representation or \code{'V'} for V-representation. Default valus is 'H'. #' #' @return A polytope class representing the \eqn{d}-dimensional unit simplex in H- or V-representation. #' @examples #' # generate a 10-dimensional simplex in H-representation #' PolyList = gen_simplex(10, 'H') #' #' # generate a 20-dimensional simplex in V-representation #' P = gen_simplex(20, 'V') #' @export gen_simplex <- function(dimension, representation = 'H') { kind_gen = 3 m_gen = 0 if (representation == "V") { Vpoly_gen = TRUE } else if (representation == "H") { Vpoly_gen = FALSE } else { stop('Not a known representation.') } Mat = poly_gen(kind_gen, Vpoly_gen, FALSE, dimension, m_gen) # first column is the vector b b = Mat[, 1] Mat = Mat[, -c(1), drop = FALSE] if (Vpoly_gen) { P = Vpolytope(V = Mat, volume = 1/prod(1:dimension)) } else { P = Hpolytope(A = -Mat, b = b, volume = 1/prod(1:dimension)) } return(P) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/gen_simplex.R
#' Generator function for skinny hypercubes #' #' This function generates a \eqn{d}-dimensional skinny hypercube \eqn{[-1,1]^{d-1}\times [-100,100]}. #' #' @param dimension The dimension of the skinny hypercube. #' #' @return A polytope class representing the \eqn{d}-dimensional skinny hypercube in H-representation. #' #' @examples #' # generate a 10-dimensional skinny hypercube. #' P = gen_skinny_cube(10) #' @export gen_skinny_cube <- function(dimension) { kind_gen = 5 m_gen = 0 Vpoly_gen = FALSE Mat = poly_gen(kind_gen, Vpoly_gen, FALSE, dimension, m_gen) # first column is the vector b b = Mat[, 1] Mat = Mat[, -c(1), drop = FALSE] P = Hpolytope(A = -Mat, b = b, volume = 2^(dimension -1)*200) return(P) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/gen_skinny_cube.R
#' Read a SDPA format file #' #' Read a SDPA format file and return a spectrahedron (an object of class Spectrahedron) which is defined by #' the linear matrix inequality in the input file, and the objective function. #' #' @param path Name of the input file #' #' @return A list with two named items: an item "matrices" which is an object of class Spectrahedron and an vector "objFunction" #' #' @examples #' path = system.file('extdata', package = 'volesti') #' l = read_sdpa_format_file(paste0(path,'/sdpa_n2m3.txt')) #' Spectrahedron = l$spectrahedron #' objFunction = l$objFunction #' @export #' @useDynLib volesti, .registration=TRUE #' @importFrom Rcpp evalCpp #' @importFrom Rcpp loadModule #' @importFrom "methods" "new" #' @exportPattern "^[[:alpha:]]+" read_sdpa_format_file <- function(path){ l = load_sdpa_format_file(path) S = Spectrahedron(matrices = l$matrices) return(list("spectrahedron"=S, "objFunction"= l$objFunction)) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/read_sdpa_file.R
#' Apply a random rotation to a convex polytope (H-polytope, V-polytope, zonotope or intersection of two V-polytopes) #' #' Given a convex H- or V- polytope or a zonotope or an intersection of two V-polytopes as input, this function applies (a) a random rotation or (b) a given rotation by an input matrix \eqn{T}. #' #' @param P A convex polytope. It is an object from class (a) Hpolytope, (b) Vpolytope, (c) Zonotope, (d) intersection of two V-polytopes. #' @param rotation A list that contains (a) the rotation matrix T and (b) the 'seed' to set a spesific seed for the number generator. #' #' @return A list that contains the rotated polytope and the matrix \eqn{T} of the linear transformation. #' #' @details Let \eqn{P} be the given polytope and \eqn{Q} the rotated one and \eqn{T} be the matrix of the linear transformation. #' \itemize{ #' \item{If \eqn{P} is in H-representation and \eqn{A} is the matrix that contains the normal vectors of the facets of \eqn{Q} then \eqn{AT} contains the normal vactors of the facets of \eqn{P}.} #' \item{If \eqn{P} is in V-representation and \eqn{V} is the matrix that contains column-wise the vertices of \eqn{Q} then \eqn{T^TV} contains the vertices of \eqn{P}.} #' \item{If \eqn{P} is a zonotope and \eqn{G} is the matrix that contains column-wise the generators of \eqn{Q} then \eqn{T^TG} contains the generators of \eqn{P}.} #' \item{If \eqn{M} is a matrix that contains column-wise points in \eqn{Q} then \eqn{T^TM} contains points in \eqn{P}.} #' } #' @examples #' # rotate a H-polytope (2d unit simplex) #' P = gen_simplex(2, 'H') #' poly_matrix_list = rotate_polytope(P) #' #' # rotate a V-polytope (3d cube) #' P = gen_cube(3, 'V') #' poly_matrix_list = rotate_polytope(P) #' #' # rotate a 5-dimensional zonotope defined by the Minkowski sum of 15 segments #' Z = gen_rand_zonotope(3, 6) #' poly_matrix_list = rotate_polytope(Z) #' @export rotate_polytope <- function(P, rotation = list()) { seed = NULL if (!is.null(rotation$seed)) { seed = rotation$seed } if (is.null(rotation$T)) { T = NULL } else { T = rotation$T } #call rcpp rotating function Mat = rotating(P, T, seed) type = P@type if (type == 'Vpolytope') { n = dim(P@V)[2] }else if (type == 'Zonotope') { n = dim(P@G)[2] } else { n = dim(P@A)[2] } m = dim(Mat)[2] - n Tr = Mat[, -c(1:(dim(Mat)[2]-n)), drop = FALSE] Tr = Tr[1:n, 1:n] Mat = t(Mat[, 1:m]) # first column is the vector b b = Mat[, 1] # remove first column A = Mat[, -c(1), drop = FALSE] if (type == 'Vpolytope') { PP = Vpolytope(V = A) }else if (type == 'Zonotope') { PP = Zonotope(G = A) } else { PP = Hpolytope(A = A, b = b) } return(list("P" = PP, "T" = Tr)) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/rotate_polytope.R
#' Apply rounding to a convex polytope (H-polytope, V-polytope or a zonotope) #' #' Given a convex H or V polytope or a zonotope as input this function brings the polytope in rounded position based on minimum volume enclosing ellipsoid of a pointset. #' #' @param P A convex polytope. It is an object from class (a) Hpolytope or (b) Vpolytope or (c) Zonotope. #' @param settings Optional. A list to parameterize the method by the random walk. #' \itemize{ #' \item{\code{random_walk} }{ The random walk to sample uniformly distributed points: (a) \code{'CDHR'} for Coordinate Directions Hit-and-Run, (b) \code{'RDHR'} for Random Directions Hit-and-Run or (c) \code{'BiW'} for Billiard walk. The default random walk is \code{'CDHR'} for H-polytopes and \code{'BiW'} for the rest of the representations.} #' \item{\code{walk_length} }{ The walk length of the random walk. The default value is \eqn{10 + 10d} for \code{'CDHR'} or \code{'RDHR'} and 2 for \code{'BiW'}.} #' \item{\code{seed} }{ Optional. A fixed seed for the number generator.} #' } #' #' @return A list with 4 elements: (a) a polytope of the same class as the input polytope class and (b) the element "T" which is the matrix of the inverse linear transformation that is applied on the input polytope, (c) the element "shift" which is the opposite vector of that which has shifted the input polytope, (d) the element "round_value" which is the determinant of the square matrix of the linear transformation that is applied on the input polytope. #' #' @references \cite{I.Z.Emiris and V. Fisikopoulos, #' \dQuote{Practical polytope volume approximation,} \emph{ACM Trans. Math. Soft.,} 2018.}, #' @references \cite{Michael J. Todd and E. Alper Yildirim, #' \dQuote{On Khachiyan’s Algorithm for the Computation of Minimum Volume Enclosing Ellipsoids,} \emph{Discrete Applied Mathematics,} 2007.} #' #' @examples #' # rotate a H-polytope (2d unit simplex) #' A = matrix(c(-1,0,0,-1,1,1), ncol=2, nrow=3, byrow=TRUE) #' b = c(0,0,1) #' P = Hpolytope(A = A, b = b) #' listHpoly = round_polytope(P) #' #' # rotate a V-polytope (3d unit cube) using Random Directions HnR with step equal to 50 #' P = gen_cube(3, 'V') #' ListVpoly = round_polytope(P) #' #' # round a 2-dimensional zonotope defined by 6 generators using ball walk #' Z = gen_rand_zonotope(2,6) #' ListZono = round_polytope(Z) #' @export round_polytope <- function(P, settings = list()){ seed = NULL if (!is.null(settings$seed)) { seed = settings$seed } ret_list = rounding(P, settings, seed) #get the matrix that describes the polytope Mat = ret_list$Mat # first column is the vector b b = Mat[, 1] # remove first column A = Mat[, -c(1), drop = FALSE] type = P@type if (type == 'Vpolytope') { PP = list("P" = Vpolytope(V = A), "T" = ret_list$T, "shift" = ret_list$shift, "round_value" = ret_list$round_value) }else if (type == 'Zonotope') { PP = list("P" = Zonotope(G = A), "T" = ret_list$T, "shift" = ret_list$shift, "round_value" = ret_list$round_value) } else { PP = list("P" = Hpolytope(A = A, b = b), "T" = ret_list$T, "shift" = ret_list$shift, "round_value" = ret_list$round_value) } return(PP) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/round_polytope.R
#' A function to over-approximate a zonotope with PCA method and to evaluate the approximation by computing a ratio of fitness. #' #' For the evaluation of the PCA method the exact volume of the approximation body is computed and the volume of the input zonotope is computed by CoolingBodies algorithm. The ratio of fitness is \eqn{R=vol(P) / vol(P_{red})}, where \eqn{P_{red}} is the approximate polytope. #' #' @param Z A zonotope. #' @param fit_ratio Optional. A boolean parameter to request the computation of the ratio of fitness. #' @param settings Optional. A list that declares the values of the parameters of CB algorithm as follows: #' \itemize{ #' \item{\code{error} }{ A numeric value to set the upper bound for the approximation error. The default value is \eqn{0.1}.} #' \item{\code{walk_length} }{ An integer to set the number of the steps for the random walk. The default value is \eqn{1}.} #' \item{\code{win_len} }{ The length of the sliding window for CB algorithm. The default value is \eqn{250}.} #' \item{\code{hpoly} }{ A boolean parameter to use H-polytopes in MMC of CB algorithm. The default value is \code{TRUE} when the order of the zonotope is \eqn{<5}, otherwise it is \code{FALSE}.} #' \item{\code{seed} }{ Optional. A fixed seed for the number generator.} #' } #' #' @return A list that contains the approximation body in H-representation and the ratio of fitness #' #' @references \cite{A.K. Kopetzki and B. Schurmann and M. Althoff, #' \dQuote{Methods for Order Reduction of Zonotopes,} \emph{IEEE Conference on Decision and Control,} 2017.} #' #' @examples #' # over-approximate a 2-dimensional zonotope with 10 generators and compute the ratio of fitness #' Z = gen_rand_zonotope(2, 8) #' retList = zonotope_approximation(Z = Z) #' #' @export zonotope_approximation <- function(Z, fit_ratio = FALSE, settings = list('error' = 0.1, 'walk_length' = 1, 'win_len' = 250, 'hpoly' = FALSE)){ seed = NULL if (!is.null(settings$seed)) { seed = settings$seed } ret_list = zono_approx(Z, fit_ratio, settings, seed) Mat = ret_list$Mat # first column is the vector b b = Mat[, 1] # remove first column A = Mat[, -c(1), drop = FALSE] PP = list("P" = Hpolytope(A = A, b = b), "fit_ratio" = ret_list$fit_ratio) return(PP) }
/scratch/gouwar.j/cran-all/cranData/volesti/R/zonotope_approximation.R
# # Helper functions to check that parameters conform the expectations # #' Check whether the object is a dataframe #' #' @keywords internal #' #' @param obj The object to test #' @param msg Optional, a custom error message #' @param stopit Whether to stop execution with an error message #' @return boolean Whether the object is a data.frame object check_is_dataframe <- function(obj, msg = NULL, stopit = TRUE) { check <-tryCatch( { is.data.frame(obj) }, error = function(e) FALSE ) if (!check && stopit) { msg <- dplyr::coalesce(msg, "Check your params: Did you provide a data frame?") stop(msg, call. = FALSE) } check <- (nrow(obj) * ncol(obj)) > 0 if (!check && stopit) { msg <- dplyr::coalesce(msg, "Check your data: Are they empty?") stop(msg, call. = FALSE) } check } #' Check whether a column exist and stop if not #' #' @keywords internal #' #' @param data A data frame #' @param col A column name #' @param msg A custom error message if the check fails #' @return boolean Whether the column exists check_has_column <- function(data, col, msg = NULL) { colname <- as.character(rlang::get_expr(rlang::enquo(col))) check <- colname != "" if (!check ) { msg <- dplyr::coalesce(msg, paste0("Did you miss to say which column to use?")) stop(msg, call. = FALSE) } check <- colname %in% colnames(data) if (!check ) { msg <- dplyr::coalesce(msg, paste0("The column ", colname, " does not exist, check your parameters.")) stop(msg, call. = FALSE) } check }
/scratch/gouwar.j/cran-all/cranData/volker/R/checks.R
#' Prepare dataframe for tabs, plots, and index operations #' #' The tibble remembers whether it was already cleaned and #' the cleaning plan is only performed once in the first call. #' #' @param data Data frame #' @param plan The cleaning plan. By now, only "sosci" is supported. See \link{data_clean_sosci}. #' @param ... Other parameters passed to the appropriate cleaning function #' @return Cleaned data frame with vlkr_df class #' @examples #' ds <- volker::chatgpt #' ds <- data_clean(ds) #' @export data_clean <- function(data, plan = "sosci", ...) { if (plan == "sosci") { data <- data_clean_sosci(data,...) } data } #' Prepare data originating from SoSci Survey #' #' The tibble remembers whether it was already prepared and #' the operations are only performed once in the first call. #' #' Prepares SoSci Survey data: #' - Remove the avector class from all columns #' (comes from SoSci and prevents combining vectors) #' - Recode residual factor values to NA (e.g. "[NA] nicht beantwortet") #' - Recode residual numeric values to NA (e.g. -9) #' - Add whitespace after slashes to better label breaks #' #' @keywords internal #' #' @param data Data frame #' @param remove.na.levels Remove residual values from factor columns. #' Either a character vector with residual values or TRUE to use defaults in \link{VLKR_NA_LEVELS} #' @param remove.na.numbers Remove residual values from numeric columns. #' Either a numeric vector with residual values or TRUE to use defaults in \link{VLKR_NA_NUMERIC} #' @param add.whitespace Add whitespace after slashes for improved label breaks #' @return Data frame with vlkr_df class (the class is used to prevent double preparation) #' @examples #' ds <- volker::chatgpt #' ds <- data_clean_sosci(ds) #' @export data_clean_sosci <- function(data, remove.na.levels = TRUE, remove.na.numbers = TRUE, add.whitespace = TRUE) { # Prepare only once if ("vlkr_df" %in% class(data)) { return (data) } # Remove avector class for (i in c(1:ncol(data))) { class(data[[i]]) <- setdiff(class(data[[i]]), "avector") } # Store codebook before mutate operations data <- labs_store(data) # Remove residual levels such as "[NA] nicht beantwortet" if (remove.na.levels != FALSE) { if (is.logical(remove.na.levels)) { remove.na.levels <- VLKR_NA_LEVELS } data <- dplyr::mutate( data, dplyr::across( tidyselect::where(~ is.factor(.)), ~ replace(., . %in% remove.na.levels, NA) ) ) } # Remove residual numbers such as -9 if (remove.na.numbers != FALSE) { if (is.logical(remove.na.numbers)) { remove.na.numbers <- VLKR_NA_NUMERIC } data <- dplyr::mutate( data, dplyr::across( dplyr::where(is.numeric), ~ dplyr::if_else(. %in% remove.na.numbers, NA, .) ) ) } # Add whitespace for better breaks if (add.whitespace) { data <- dplyr::mutate( data, dplyr::across( tidyselect::where(is.character), ~ stringr::str_replace_all(., stringr::fixed("/"), "/\u200B") ) ) data <- dplyr::mutate( data, dplyr::across( tidyselect::where(is.factor), ~ forcats::fct_relabel(., ~ stringr::str_replace_all(., stringr::fixed("/"), "/\u200B")) ) ) } # Restore codebook data <- labs_restore(data) .to_vlkr_df(data) } #' Add vlkr_df class - that means, the data frame has been prepared #' #' @keywords internal #' #' @param data A tibble #' @return A tibble of class vlkr_df .to_vlkr_df <- function(data, digits = NULL) { data <- dplyr::as_tibble(data) class(data) <- c("vlkr_df", setdiff(class(data), "vlkr_df")) data }
/scratch/gouwar.j/cran-all/cranData/volker/R/clean.R
# # Constants # #' Levels to remove from factors #' #' By default the value `[NA] nicht beantwortet` is removed from tables and plots #' #' @keywords internal VLKR_NA_LEVELS <- c("[NA] nicht beantwortet") #' Numbers to remove from vectors #' #' By default the value `-9` is removed from tables and plots #' #' @keywords internal VLKR_NA_NUMERIC <- c(-9) # Plot settings VLKR_POINTCOLOR <- "darkcyan" #"#611F53FF" VLKR_FILLCOLOR <- "darkcyan" #"#611F53FF" VLKR_FILLGRADIENT <- c("#e5f7ff", "#96dfde", "#008b8b", "#006363", "black") VLKR_LOWPERCENT <- 5 VLKR_PLOT_DPI <- 192 VLKR_PLOT_SCALE <- 96 VLKR_PLOT_WIDTH <- 910 VLKR_PLOT_PXPERLINE <- 15 VLKR_PLOT_OFFSETROWS <- 5 VLKR_PLOT_TITLEROWS <- 2 VLKR_PLOT_LABELWRAP <- 40
/scratch/gouwar.j/cran-all/cranData/volker/R/config.R
#' ChatGPT Adoption Dataset CG-GE-APR22 #' #' A small random subset of data from a survey about ChatGPT #' adoption. The survey was conducted in April 2023 within #' the population of Germany Internet users. #' #' Call codebook(volker::chatgpt) to see the items and and answer options. #' #' @format ## `chatgpt` #' A data frame with 101 rows and 19 columns: #' \describe{ #' \item{case}{A running case number} #' \item{adopter}{Adoption groups inspired by Roger's innovator typology.} #' \item{use_}{Columns starting with use contain data about ChatGPT usage in different contexts.} #' \item{cg_activities}{Text answers to the question, what the respondents do with ChatGPT.} #' \item{cg_adoption_}{A scale consisting of items about advantages, fears, and social aspects. #' The scales match theoretical constructs inspired by Roger's diffusion model and Davis' Technology Acceptance Model} #' \item{sd_}{Columns starting with sd contain sociodemographics of the respondents.} #' } #' @source Communication Department of the University of Münster (<[email protected]>). "chatgpt"
/scratch/gouwar.j/cran-all/cranData/volker/R/data.R
# # Functions to handle indexes # #' Calculate the mean value of multiple items #' #' @param data A dataframe #' @param cols A tidy selection of item columns #' @param newcol Name of the index as a character value. #' Set to NULL (default) to automatically build a name #' from the common column prefix, prefixed with "idx_" #' @param negative If FALSE (default), negative values are recoded as missing values. #' @param clean Prepare data by \link{data_clean}. #' @return The input tibble with an additional column that contains the index values. #' The column contains the result of the alpha calculation in the attribute named "psych.alpha". #' @examples #' ds <- volker::chatgpt #' volker::idx_add(ds, starts_with("cg_adoption")) #' @export #' @importFrom rlang .data idx_add <- function(data, cols, newcol = NULL, negative = FALSE, clean = TRUE) { # 1. Checks check_is_dataframe(data) # 2. Clean if (clean) { data <- data_clean(data) } idx <- data %>% dplyr::select({{ cols }}) # Remove negative values # TODO: warn if any negative values were recoded if (!negative) { idx <- dplyr::mutate(idx, dplyr::across(tidyselect::where(is.numeric), ~ ifelse(. < 0, NA, .))) } # Remove missings # TODO: output a warning # data <- data %>% # tidyr::drop_na({{ cols }}) prefix <- get_prefix(colnames(idx), FALSE, TRUE) if (is.null(newcol)) { newcol <- paste0("idx_", prefix) } # Create a label newlabel <- codebook(idx) %>% dplyr::distinct(dplyr::across(tidyselect::all_of("item_label"))) %>% stats::na.omit() %>% dplyr::pull(.data$item_label) %>% get_prefix(FALSE, TRUE) if (is.na(newlabel)) { newlabel <- prefix } newlabel <- paste0("Index: ", prefix) idx <- idx %>% psych::alpha(check.keys = TRUE) data[[newcol]] <- idx$scores attr(data[[newcol]], "psych.alpha") <- idx attr(data[[newcol]], "comment") <- newlabel # Add limits attr(data[[newcol]], "limits") <- get_limits(data, {{ cols }}, negative) # Add scale attr(data[[newcol]], "scale") <- data %>% codebook({{ cols }}) %>% dplyr::distinct(dplyr::across(tidyselect::all_of(c("value_name", "value_label")))) data } #' Get number of items and Cronbach's alpha of a scale added by idx_add() #' #' @keywords internal #' #' @param data A data frame column #' @return A named list with with the keys "items" and "alpha" idx_alpha <- function(data) { idx <- attr(data, "psych.alpha") if (!is.null(idx)) { return(list("items" = idx$nvar, "alpha" = idx$total$std.alpha)) } return(list("items" = NA, "alpha" = NA)) }
/scratch/gouwar.j/cran-all/cranData/volker/R/idx.R
# Standalone file: do not edit by hand # Source: <https://github.com/r-lib/rlang/blob/main/R/standalone-purrr.R> # ---------------------------------------------------------------------- # # --- # repo: r-lib/rlang # file: standalone-purrr.R # last-updated: 2023-02-23 # license: https://unlicense.org # imports: rlang # --- # # This file provides a minimal shim to provide a purrr-like API on top of # base R functions. They are not drop-in replacements but allow a similar style # of programming. # # ## Changelog # # 2023-02-23: # * Added `list_c()` # # 2022-06-07: # * `transpose()` is now more consistent with purrr when inner names # are not congruent (#1346). # # 2021-12-15: # * `transpose()` now supports empty lists. # # 2021-05-21: # * Fixed "object `x` not found" error in `imap()` (@mgirlich) # # 2020-04-14: # * Removed `pluck*()` functions # * Removed `*_cpl()` functions # * Used `as_function()` to allow use of `~` # * Used `.` prefix for helpers # # nocov start map <- function(.x, .f, ...) { .f <- as_function(.f, env = global_env()) lapply(.x, .f, ...) } walk <- function(.x, .f, ...) { map(.x, .f, ...) invisible(.x) } map_lgl <- function(.x, .f, ...) { .rlang_purrr_map_mold(.x, .f, logical(1), ...) } map_int <- function(.x, .f, ...) { .rlang_purrr_map_mold(.x, .f, integer(1), ...) } map_dbl <- function(.x, .f, ...) { .rlang_purrr_map_mold(.x, .f, double(1), ...) } map_chr <- function(.x, .f, ...) { .rlang_purrr_map_mold(.x, .f, character(1), ...) } .rlang_purrr_map_mold <- function(.x, .f, .mold, ...) { .f <- as_function(.f, env = global_env()) out <- vapply(.x, .f, .mold, ..., USE.NAMES = FALSE) names(out) <- names(.x) out } map2 <- function(.x, .y, .f, ...) { .f <- as_function(.f, env = global_env()) out <- mapply(.f, .x, .y, MoreArgs = list(...), SIMPLIFY = FALSE) if (length(out) == length(.x)) { set_names(out, names(.x)) } else { set_names(out, NULL) } } map2_lgl <- function(.x, .y, .f, ...) { as.vector(map2(.x, .y, .f, ...), "logical") } map2_int <- function(.x, .y, .f, ...) { as.vector(map2(.x, .y, .f, ...), "integer") } map2_dbl <- function(.x, .y, .f, ...) { as.vector(map2(.x, .y, .f, ...), "double") } map2_chr <- function(.x, .y, .f, ...) { as.vector(map2(.x, .y, .f, ...), "character") } imap <- function(.x, .f, ...) { map2(.x, names(.x) %||% seq_along(.x), .f, ...) } pmap <- function(.l, .f, ...) { .f <- as.function(.f) args <- .rlang_purrr_args_recycle(.l) do.call("mapply", c( FUN = list(quote(.f)), args, MoreArgs = quote(list(...)), SIMPLIFY = FALSE, USE.NAMES = FALSE )) } .rlang_purrr_args_recycle <- function(args) { lengths <- map_int(args, length) n <- max(lengths) stopifnot(all(lengths == 1L | lengths == n)) to_recycle <- lengths == 1L args[to_recycle] <- map(args[to_recycle], function(x) rep.int(x, n)) args } keep <- function(.x, .f, ...) { .x[.rlang_purrr_probe(.x, .f, ...)] } discard <- function(.x, .p, ...) { sel <- .rlang_purrr_probe(.x, .p, ...) .x[is.na(sel) | !sel] } map_if <- function(.x, .p, .f, ...) { matches <- .rlang_purrr_probe(.x, .p) .x[matches] <- map(.x[matches], .f, ...) .x } .rlang_purrr_probe <- function(.x, .p, ...) { if (is_logical(.p)) { stopifnot(length(.p) == length(.x)) .p } else { .p <- as_function(.p, env = global_env()) map_lgl(.x, .p, ...) } } compact <- function(.x) { Filter(length, .x) } transpose <- function(.l) { if (!length(.l)) { return(.l) } inner_names <- names(.l[[1]]) if (is.null(inner_names)) { fields <- seq_along(.l[[1]]) } else { fields <- set_names(inner_names) .l <- map(.l, function(x) { if (is.null(names(x))) { set_names(x, inner_names) } else { x } }) } # This way missing fields are subsetted as `NULL` instead of causing # an error .l <- map(.l, as.list) map(fields, function(i) { map(.l, .subset2, i) }) } every <- function(.x, .p, ...) { .p <- as_function(.p, env = global_env()) for (i in seq_along(.x)) { if (!rlang::is_true(.p(.x[[i]], ...))) { return(FALSE) } } TRUE } some <- function(.x, .p, ...) { .p <- as_function(.p, env = global_env()) for (i in seq_along(.x)) { if (rlang::is_true(.p(.x[[i]], ...))) { return(TRUE) } } FALSE } negate <- function(.p) { .p <- as_function(.p, env = global_env()) function(...) !.p(...) } reduce <- function(.x, .f, ..., .init) { f <- function(x, y) .f(x, y, ...) Reduce(f, .x, init = .init) } reduce_right <- function(.x, .f, ..., .init) { f <- function(x, y) .f(y, x, ...) Reduce(f, .x, init = .init, right = TRUE) } accumulate <- function(.x, .f, ..., .init) { f <- function(x, y) .f(x, y, ...) Reduce(f, .x, init = .init, accumulate = TRUE) } accumulate_right <- function(.x, .f, ..., .init) { f <- function(x, y) .f(y, x, ...) Reduce(f, .x, init = .init, right = TRUE, accumulate = TRUE) } detect <- function(.x, .f, ..., .right = FALSE, .p = is_true) { .p <- as_function(.p, env = global_env()) .f <- as_function(.f, env = global_env()) for (i in .rlang_purrr_index(.x, .right)) { if (.p(.f(.x[[i]], ...))) { return(.x[[i]]) } } NULL } detect_index <- function(.x, .f, ..., .right = FALSE, .p = is_true) { .p <- as_function(.p, env = global_env()) .f <- as_function(.f, env = global_env()) for (i in .rlang_purrr_index(.x, .right)) { if (.p(.f(.x[[i]], ...))) { return(i) } } 0L } .rlang_purrr_index <- function(x, right = FALSE) { idx <- seq_along(x) if (right) { idx <- rev(idx) } idx } list_c <- function(x) { inject(c(!!!x)) } # nocov end
/scratch/gouwar.j/cran-all/cranData/volker/R/import-standalone-purrr.R
#' Get variable labels from their comment attributes #' #' @param data A tibble #' @param cols A tidy variable selections to filter specific columns #' @return A tibble with the columns: #' - item_name: The column name. #' - item_group: First part of the column name, up to an underscore. #' - item_class: The last class value of an item (e.g. numeric, factor). #' - item_label: The comment attribute of the column. #' - value_name: In case a column has numeric attributes, the attribute names #' - value_label: In case a column has numeric attributes or T/F-attributes, #' the attribute values. #' In case a column has a levels attribute, the levels. #' @examples #' volker::codebook(volker::chatgpt) #' @importFrom rlang .data #' @export codebook <- function(data, cols) { if (!missing(cols)) { data <- dplyr::select(data, {{ cols }}) } # Replace empty classes with NA item_classes <- sapply(data, attr, "class", simplify = FALSE) item_classes <- ifelse(sapply(item_classes, is.null), NA, item_classes) item_comments <- sapply(data, attr, "comment", simplify = FALSE) item_comments <- ifelse(sapply(item_comments, is.null), NA, item_comments) labels <- dplyr::tibble( item_name = colnames(data), item_class = item_classes, item_label = item_comments, value_label = lapply(data, attributes) ) %>% dplyr::mutate(item_label = as.character(sapply(.data$item_label, function(x) ifelse(is.null(x), NA, x)))) %>% dplyr::mutate(item_label = ifelse(is.na(.data$item_label), .data$item_name, .data$item_label)) %>% dplyr::mutate(item_group = stringr::str_remove(.data$item_name, "_.*")) %>% dplyr::mutate(item_class = as.character(sapply(.data$item_class, function(x) ifelse(length(x) > 1, x[[length(x)]], x)))) %>% dplyr::select(tidyselect::all_of(c("item_name", "item_group", "item_class", "item_label", "value_label"))) %>% tidyr::unnest_longer(tidyselect::all_of("value_label"), keep_empty = TRUE) if ("value_label_id" %in% colnames(labels)) { # Get items with codes labels_codes <- labels %>% dplyr::rename(value_name = tidyselect::all_of("value_label_id")) %>% # dplyr::filter(!(value_name %in% c("comment", "class","levels","tzone"))) %>% dplyr::filter(stringr::str_detect(.data$value_name, "^-?[0-9TF]+$")) %>% dplyr::mutate(value_label = as.character(.data$value_label)) %>% dplyr::select(tidyselect::all_of(c("item_name", "item_group", "item_class", "item_label", "value_name", "value_label"))) labels_levels <- labels %>% # dplyr::rename(value_name = value_label_id) %>% dplyr::filter(.data$value_label_id == "levels") %>% dplyr::select(tidyselect::all_of(c("item_group", "item_class", "item_name", "item_label", "value_label"))) |> tidyr::unnest_longer(tidyselect::all_of("value_label")) %>% dplyr::mutate(value_label = as.character(.data$value_label)) # Combine items without codes and items with codes labels <- labels %>% dplyr::distinct(dplyr::across(tidyselect::all_of(c("item_name", "item_group", "item_class", "item_label")))) %>% dplyr::anti_join(labels_codes, by = "item_name") %>% dplyr::bind_rows(labels_codes) %>% dplyr::anti_join(labels_levels, by = "item_name") %>% dplyr::bind_rows(labels_levels) } else { labels$value_name <- NA } # Detect groups # TODO: revise group detection. Will be used for index calculation. # groups <- labels %>% # dplyr::distinct(item_name) %>% # dplyr::mutate( # item_prefix = get_prefix(item_name), # item_postfix = stringr::str_sub(item_name, stringr::str_length(item_prefix) + 1) # ) %>% # dplyr::arrange(item_postfix) %>% # dplyr::mutate( # item_next = dplyr::lead(item_postfix), # item_prev = dplyr::lag(item_postfix) # ) %>% # dplyr::rowwise() %>% # dplyr::mutate( # item_infix = ifelse(!is.na(item_next),get_prefix(c(item_postfix, item_next)), ""), # item_infix = ifelse(item_infix == "",get_prefix(c(item_postfix, item_prev)), item_infix), # ) %>% # dplyr::ungroup() %>% # dplyr::mutate(item_postfix = stringr::str_sub(item_postfix, stringr::str_length(item_infix) + 1)) %>% # dplyr::select(item_name, item_prefix, item_infix, item_postfix) # # labels <- dplyr::left_join(labels, groups, by="item_name") labels } #' Get the current codebook and store it in the codebook attribute. #' #' You can restore the labels after mutate operations by calling #' \link{labs_restore}. #' #' @param data A data frame #' @return A data frame #' @examples #' library(dplyr) #' library(volker) #' #' volker::chatgpt |> #' labs_store() |> #' mutate(sd_age = 2024 - sd_age) |> #' labs_restore() |> #' tab_metrics(sd_age) #' @export labs_store <- function(data) { codes <- codebook(data) attr(data,"codebook") <- codes data } #' Restore labels from the codebook store in the codebook attribute. #' #' You can store labels before mutate operations by calling #' \link{labs_store}. #' #' @param data A data frame #' @param cols A tidyselect column selection #' @param values If TRUE (default), restores value labels in addition to item labels. #' Item labels correspond to columns, value labels to values in the columns. #' @return A data frame #' @examples #' library(dplyr) #' library(volker) #' #' volker::chatgpt |> #' labs_store() |> #' mutate(sd_age = 2024 - sd_age) |> #' labs_restore() |> #' tab_metrics(sd_age) #' @export labs_restore <- function(data, cols = NULL, values = TRUE) { codes <- attr(data,"codebook") if (is.data.frame(codes)) { data <- labs_apply(data, codes, {{ cols }}, values) } else { warning("No codebook found in the attributes.") } data } #' Set variable labels by setting their comment attributes #' #' @param data A tibble #' @param codes A tibble in \link{codebook} format. #' To set column labels, use item_name and item_label columns. #' @param cols A tidy column selection. Set to NULL (default) to apply to all columns #' found in the codebook. #' Restricting the columns is helpful when you want to set value labels. #' In this case, provide a tibble with value_name and value_label columns #' and specify the columns that should be modified. #' @param values If TRUE (default), sets value labels. #' - For factors: Factor levels and order are retrieved #' from the value_label column. #' - For item values: they are retrieved from both the columns #' value_name and value_label in your codebook. #' @return A tibble with new labels #' @examples #' library(tibble) #' library(volker) #' #' newlabels <- tribble( #' ~item_name, ~item_label, #' "cg_adoption_advantage_01", "Allgemeine Vorteile", #' "cg_adoption_advantage_02", "Finanzielle Vorteile", #' "cg_adoption_advantage_03", "Vorteile bei der Arbeit", #' "cg_adoption_advantage_04", "Macht mehr Spaß" #' ) #' #' volker::chatgpt %>% #' labs_apply(newlabels) %>% #' tab_metrics(starts_with("cg_adoption_advantage_")) #' @importFrom rlang .data #' @export labs_apply <- function(data, codes, cols = NULL, values = TRUE) { # Check if ((nrow(codes) ==0)) { return (data) } # Fix column names if (!"item_name" %in% colnames(codes) && (colnames(codes)[1] != "value_name")) { colnames(codes)[1] <- "item_name" } if (!"item_label" %in% colnames(codes) && (colnames(codes)[2] != "value_label")) { colnames(codes)[2] <- "item_label" } # Can only set item or value labels if present in the codebook items <- ("item_name" %in% colnames(codes)) && ("item_label" %in% colnames(codes)) values <- values && ("value_name" %in% colnames(codes)) && ("value_label" %in% colnames(codes)) # Set column labels (= comment attributes) if (items) { lastitem <- "" for (no in c(1:nrow(codes))) { item_name <- codes$item_name[no] if (item_name %in% colnames(data) & (item_name != lastitem)) { comment(data[[item_name]]) <- codes$item_label[no] } lastitem <- item_name } } # Set value labels if (values) { if (!rlang::quo_is_symbol(rlang::enquo(cols)) || missing(cols) || is.null(cols)) { cols <- data |> colnames() } else { cols <- dplyr::select(data, {{ cols }}) |> colnames() } for (col in cols) { value_rows <- codes if ("item_name" %in% colnames(value_rows)) { value_rows <- value_rows |> dplyr::filter(.data$item_name == col) } value_rows <- value_rows |> dplyr::select(tidyselect::any_of(c("value_name", "value_label","item_class"))) |> dplyr::filter( !is.null(.data$value_name), !is.null(.data$value_label), !is.na(.data$value_name), !is.na(.data$value_label) ) if (nrow(value_rows) > 0) { value_factor <- ("item_class" %in% colnames(value_rows)) && any(value_rows$item_class == "factor", na.rm= TRUE) # Factor order if (value_factor) { value_levels <- unique(value_rows$value_label) current_levels <- unique(data[[col]]) if (length(setdiff(current_levels, value_levels)) > 0) { warning(paste0( "Check your levels: Not all factor levels of ", col, " are present in the codebook. The old levels were kept.") ) } else { data[[col]] <- factor(data[[col]], levels=value_levels) } } # Item labeling else { for (vr in c(1:nrow(value_rows))) { value_name <- value_rows$value_name[vr] value_label <- value_rows$value_label[vr] attr(data[[col]], as.character(value_name)) <- value_label } } } } } data } #' Remove all comments from the selected columns #' #' @param data A tibble #' @param cols Tidyselect columns #' @param labels The attributes to remove. NULL to remove all attributes except levels and class #' @return A tibble with comments removed #' @examples #' library(volker) #' volker::chatgpt |> #' labs_clear() #' @export labs_clear <- function(data, cols, labels = NULL) { remove_attr <- function(x, labels = NULL) { if (is.null(labels)) { labels <- setdiff(names(attributes(x)), c("class", "levels")) } for (label in labels) { attr(x, label) <- NULL } x } if (missing(cols)) { data <- dplyr::mutate(data, dplyr::across(tidyselect::everything(), ~remove_attr(., labels))) } else { data <- dplyr::mutate(data, dplyr::across({{ cols }}, ~remove_attr(., labels))) } data } #' Replace item names in a column by their labels #' #' TODO: Make dry with labs_replace_values #' #' @keywords internal #' #' @param data A tibble #' @param col The column holding item names #' @param codes The codebook to use: A tibble with the columns item_name and item_label. #' Can be created by the \link{codebook} function, e.g. by calling #' `codes <- codebook(data, myitemcolumn)`. #' @return Tibble with new labels #' @importFrom rlang .data labs_replace_names <- function(data, col, codes) { # Column without quotes # TODO: could we just use "{{ col }}" with quotes in mutate below? # See example at https://rlang.r-lib.org/reference/topic-data-mask-ambiguity.html if (rlang::quo_is_symbol(rlang::enquo(col))) { col <- rlang::enquo(col) } # Column as character else { col <- rlang::sym(col) } codes <- codes %>% dplyr::distinct(dplyr::across(tidyselect::all_of(c("item_name", "item_label")))) %>% dplyr::rename(.name = tidyselect::all_of("item_name"), .label = tidyselect::all_of("item_label")) %>% stats::na.omit() if (nrow(codes) > 0) { data <- data %>% dplyr::mutate(.name = !!col) %>% dplyr::left_join(codes, by = ".name") %>% dplyr::mutate(!!col := dplyr::coalesce(.data$.label, .data$.name)) %>% dplyr::select(-tidyselect::all_of(c(".name", ".label"))) } data } #' Replace item value names in a column by their labels #' #' TODO: Make dry with labs_replace_names #' #' @keywords internal #' #' @param data A tibble #' @param col The column holding item values #' @param codes The codebook to use: A tibble with the columns value_name and value_label. #' Can be created by the \link{codebook} function, e.g. by calling #' `codes <- codebook(data, myitemcolumn)`. #' @return Tibble with new labels labs_replace_values <- function(data, col, codes) { # Column without quotes if (rlang::quo_is_symbol(rlang::enquo(col))) { col <- rlang::enquo(col) } # Column as character else { col <- rlang::sym(col) } levels_before <- data |> dplyr::select(!! col) |> dplyr::pull(1) |> as.character() |> unique() codes <- codes %>% dplyr::filter(as.character(.data$value_name) %in% levels_before) |> dplyr::distinct(dplyr::across(tidyselect::all_of(c("value_name", "value_label")))) %>% dplyr::rename(.name = tidyselect::all_of("value_name"), .label = tidyselect::all_of("value_label")) %>% stats::na.omit() if (nrow(codes) > 0) { data <- data %>% dplyr::mutate(.name = !!col ) %>% dplyr::left_join(codes, by = ".name") %>% dplyr::mutate(!!col := dplyr::coalesce(.data$.label, .data$.name)) data <- data |> dplyr::mutate(!!col := factor(!!col, levels=codes$.label)) data <- data %>% dplyr::select(-tidyselect::all_of(c(".name", ".label"))) } data } #' Get a common title for a column selection #' #' @keywords internal #' #' @param data A tibble #' @param cols A tidy column selection #' @return A character string #' @importFrom rlang .data get_title <- function(data, cols) { labels <- data %>% codebook({{ cols }}) %>% tidyr::drop_na("item_label") if (nrow(labels) > 0) { labels <- labels$item_label } else { labels <- dplyr::select(data, {{ cols }}) %>% colnames() } labels %>% get_prefix() %>% trim_label() } #' Get the numeric range from the labels #' #' @keywords internal #' #' @param data The labeled data frame #' @param cols A tidy variable selection #' @param negative Whether to include negative values #' @return A list or NULL #' @importFrom rlang .data get_limits <- function(data, cols, negative = FALSE) { # First, try to get limits from the column attributes values <- data %>% dplyr::select({{ cols }}) %>% lapply(attr, "limits") %>% unlist() # Second, try to get limits from the column labels if (is.null(values)) { values <- codebook(data, {{ cols }}) %>% dplyr::distinct(dplyr::across(tidyselect::all_of("value_name"))) %>% dplyr::pull(.data$value_name) values <- suppressWarnings(as.numeric(values)) } # Third, try to get limits from the column values if (is.null(values) | all(is.na(values))) { values <- data %>% dplyr::select({{ cols }}) %>% unlist() values <- suppressWarnings(as.numeric(values)) } if (all(is.na(values))) { return(NULL) } if (!negative) { values <- suppressWarnings(values[values >= 0]) } if (any(!is.na(values))) { return(range(values, na.rm = TRUE)) } return(NULL) } #' Detect whether a scale is a numeric sequence #' #' From all values in the selected columns, the numbers are extracted. #' If no numeric values can be found, returns 0. #' Otherwise, if any positive values form an ascending sequence, returns -1. #' In all other cases, returns 1. #' #' @keywords internal #' #' @param data The dataframe #' @param cols The tidy selection #' @param extract Whether to extract numeric values from characters #' @return 0 = an undirected scale, -1 = descending values, 1 = ascending values #' @importFrom rlang .data get_direction <- function(data, cols, extract = TRUE) { data <- dplyr::select(data, {{ cols }}) # Get all values categories <- data %>% dplyr::mutate(dplyr::across(tidyselect::everything(), as.character)) %>% tidyr::pivot_longer(tidyselect::everything()) %>% dplyr::arrange(.data$value) %>% dplyr::mutate(value = ifelse(extract, stringr::str_extract(.data$value, "[0-9-]+"), .data$value)) %>% dplyr::distinct(dplyr::across(tidyselect::all_of("value"))) %>% dplyr::pull(.data$value) # Detect whether the categories are a numeric sequence and choose direction scale_numeric <- data %>% sapply(is.numeric) %>% all() scale_ordered <- suppressWarnings(as.numeric(c(categories))) scale_positive <- scale_ordered[scale_ordered >= 0] if (!scale_numeric && all(is.na(scale_ordered))) { categories_scale <- 0 } else if (any(diff(scale_positive) >= 0) | any(is.na(scale_ordered))) { categories_scale <- -1 } else { categories_scale <- 1 } categories_scale } #' Get the common prefix of character values #' #' Helper function taken from the biobase package. #' Duplicated here instead of loading the package to avoid overhead. #' See https://github.com/Bioconductor/Biobase #' #' @keywords internal #' #' @param x Character vector #' @param ignore.case Whether case matters (default) #' @param trim Whether non alphabetic characters should be trimmed #' @return The longest common prefix of the strings get_prefix <- function(x, ignore.case = FALSE, trim = FALSE) { x <- as.character(x) if (ignore.case) { x <- toupper(x) } x <- stats::na.omit(x) if (length(x) == 0) { return (NA) } if (length(x) == 1) { return (x) } nc <- nchar(x, type = "char") for (i in 1:min(nc)) { ss <- substr(x, 1, i) if (any(ss != ss[1])) { prefix <- substr(x[1], 1, i - 1) if (trim) { prefix <- trim_label(prefix) } return(prefix) } } prefix <- trim_label(substr(x[1], 1, i)) if (trim) { prefix <- trim_label(prefix) } prefix } #' Remove trailing zeros and trailing or leading #' whitespaces, colons, #' hyphens and underscores #' #' @keywords internal #' #' @param x A character value #' @return The trimmed character value trim_label <- function(x) { x <- stringr::str_remove(x, "[: 0_-]*$") x <- stringr::str_remove(x, "^[: _-]*") x } #' Prepare the scale attribute values #' #' @keywords internal #' #' @param data A tibble with a scale attribute #' @return A named list or NULL #' @importFrom rlang .data prepare_scale <- function(data) { if (!is.null(data)) { data <- data %>% dplyr::mutate(value_name = suppressWarnings(as.numeric(.data$value_name))) %>% dplyr::filter(.data$value_name >= 0) %>% stats::na.omit() scale <- stats::setNames( as.character(data$value_label), as.character(data$value_name) ) return(scale) } return(NULL) } #' Wrap labels in plot scales #' #' @keywords internal label_scale <- function(x, scale) { ifelse( x %in% names(scale), stringr::str_wrap(scale[as.character(x)], width = 10), x ) }
/scratch/gouwar.j/cran-all/cranData/volker/R/labels.R
#' Output a frequency plot #' #' The type of frequency plot depends on the number of selected columns: #' - One column: see \link{plot_counts_one} #' - Multiple columns: see \link{plot_counts_items} #' - One column and one grouping column: see \link{plot_counts_one_grouped} #' - Multiple columns and one grouping column: see \link{plot_counts_items_grouped} #' #' #' @param data A data frame #' @param cols A tidy column selection, #' e.g. a single column (without quotes) #' or multiple columns selected by methods such as starts_with() #' @param col_group Optional, a grouping column. The column name without quotes. #' @param clean Prepare data by \link{data_clean}. #' @param ... Other parameters passed to the appropriate plot function #' @return A ggplot2 plot object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' plot_counts(data, sd_gender) #' #' @export plot_counts <- function(data, cols, col_group = NULL, clean = TRUE, ...) { # Check check_is_dataframe(data) # Find columns cols_eval <- tidyselect::eval_select(expr = enquo(cols), data = data) col_group_eval <- tidyselect::eval_select(expr = enquo(col_group), data = data) is_items <- length(cols_eval) > 1 is_grouped <- length(col_group_eval)== 1 # Single variables if (!is_items && !is_grouped) { plot_counts_one(data, {{ cols }}, ...) } else if (!is_items && is_grouped) { plot_counts_one_grouped(data, {{ cols }}, {{ col_group }}, ...) } # Items else if (is_items && !is_grouped) { plot_counts_items(data, {{ cols }} , ...) } else if (is_items && is_grouped) { plot_counts_items_grouped(data, {{ cols }}, {{ col_group }}, ...) } # Not found else { stop("Check your parameters: the column selection is not supported by volker functions.") } } #' Output a plot with distribution parameters such as the mean values #' #' The table type depends on the number of selected columns: #' - One column: see \link{plot_metrics_one} #' - Multiple columns: see \link{plot_metrics_items} #' - One column and one grouping column: see \link{plot_metrics_one_grouped} #' - Multiple columns and one grouping column: see \link{plot_metrics_items_grouped} #' #' @param data A data frame #' @param cols A tidy column selection, #' e.g. a single column (without quotes) #' or multiple columns selected by methods such as starts_with(). #' @param col_group Optional, a grouping column (without quotes). #' @param clean Prepare data by \link{data_clean}. #' @param ... Other parameters passed to the appropriate plot function #' @return A ggplot object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' plot_metrics(data, sd_age) #' #' @export plot_metrics <- function(data, cols, col_group = NULL, clean = TRUE, ...) { # Check check_is_dataframe(data) # Find columns cols_eval <- tidyselect::eval_select(expr = enquo(cols), data = data) col_group_eval <- tidyselect::eval_select(expr = enquo(col_group), data = data) is_items <- length(cols_eval) > 1 is_grouped <- length(col_group_eval)== 1 # Single variables if (!is_items && !is_grouped) { plot_metrics_one(data, {{ cols }}, ...) } else if (!is_items && is_grouped) { plot_metrics_one_grouped(data, {{ cols }}, {{ col_group }}, ...) } # Items else if (is_items && !is_grouped) { plot_metrics_items(data, {{ cols }} , ...) } else if (is_items && is_grouped) { plot_metrics_items_grouped(data, {{ cols }}, {{ col_group }}, ...) } # Not found else { stop("Check your parameters: the column selection is not supported by volker functions.") } } #' Plot the frequency of values in one column. #' #' Note: only non-missing cases are used to calculate the percentage. #' #' @keywords internal #' #' @param data A tibble #' @param col The column holding values to count #' @param missings Include missing values (default FALSE) #' @param numbers The values to print on the bars: "n" (frequency), "p" (percentage) or both. #' @param title If TRUE (default) shows a plot title derived from the column labels. #' Disable the title with FALSE or provide a custom title as character value. #' @param labels If TRUE (default) extracts labels from the attributes, see \link{codebook}. #' @param clean Prepare data by \link{data_clean}. #' @param ... Placeholder to allow calling the method with unused parameters from \link{plot_counts}. #' @return A ggplot object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' plot_counts_one(data, sd_gender) #' #' @importFrom rlang .data #' @export plot_counts_one <- function(data, col, missings = FALSE, numbers = NULL, title = TRUE, labels = TRUE, clean = TRUE, ...) { # 1. Checks # Check columns check_is_dataframe(data) check_has_column(data, {{ col }}) # 2. Clean if (clean) { data <- data_clean(data) } if (!missings) { data <- data %>% tidyr::drop_na({{ col }}) } # 3. Data # Count data result <- data %>% dplyr::count({{ col }}) %>% dplyr::mutate(p = (.data$n / sum(.data$n)) * 100) # Numbers result <- result %>% dplyr::mutate( .values = dplyr::case_when( .data$p < VLKR_LOWPERCENT ~ "", all(numbers == "n") ~ as.character(.data$n), all(numbers == "p") ~ paste0(round(.data$p, 0), "%"), TRUE ~ paste0(.data$n, "\n", round(.data$p, 0), "%") ) ) # Item labels result <- result |> dplyr::mutate( "{{ col }}" := as.factor({{ col }})) if (labels) { result <- labs_replace_values(result, {{ col }}, codebook(data, {{ col }})) } # 3. Plot # TODO: Make dry, see plot_item_counts and tab_group_counts pl <- result %>% ggplot2::ggplot(ggplot2::aes({{ col }}, y = .data$p / 100)) + ggplot2::geom_col(fill = VLKR_FILLCOLOR) + # TODO: make limits configurable # scale_y_continuous(limits =c(0,100), labels=c("0%","25%","50%","75%","100%")) + ggplot2::scale_y_continuous(labels = scales::percent) + ggplot2::scale_x_discrete(limits=rev) + ggplot2::ylab("Share in percent") + ggplot2::coord_flip() + ggplot2::theme( axis.title.x = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank(), axis.text.y = ggplot2::element_text(size = 11), legend.title = ggplot2::element_blank(), plot.title.position = "plot", plot.caption = ggplot2::element_text(hjust = 0), plot.caption.position = "plot" ) # Plot numbers if (!is.null(numbers)) { pl <- pl + ggplot2::geom_text( ggplot2::aes(label = .data$.values), position = ggplot2::position_stack(vjust = 0.5), size = 3, color = "white" ) } # Title if (title == TRUE) { title <- get_title(data, {{ col }}) } else if (title == FALSE) { title <- NULL } if (!is.null(title)) { pl <- pl + ggplot2::ggtitle(label = title) } # Base # TODO: report missing cases base_n <- nrow(data) pl <- pl + ggplot2::labs(caption = paste0("n=", base_n)) # Pass row number and label length to the knit_plot() function .to_vlkr_plot(pl) } #' Plot frequencies cross tabulated with a grouping column #' #' Note: only non-missing cases are used to calculate the percentage. #' #' @keywords internal #' #' @param data A tibble #' @param col The column holding factor values #' @param col_group The column holding groups to compare #' @param ordered Values can be nominal (0) or ordered ascending (1) descending (-1). #' By default (NULL), the ordering is automatically detected. #' An appropriate color scale should be choosen depending on the ordering. #' For unordered values, the default scale is used. #' For ordered values, shades of the VLKR_FILLGRADIENT option are used. #' @param category The value FALSE will force to plot all categories. #' A character value will focus a selected category. #' When NULL, in case of boolean values, only the TRUE category is plotted. #' @param missings Include missing values (default FALSE) #' @param prop The basis of percent calculation: "total" (the default), "rows" or "cols". #' Plotting row or column percentages results in stacked bars that add up to 100%. #' Whether you set rows or cols determines which variable is in the legend (fill color) #' and which on the vertical scale. #' @param numbers The numbers to print on the bars: "n" (frequency), "p" (percentage) or both. #' @param title If TRUE (default) shows a plot title derived from the column labels. #' Disable the title with FALSE or provide a custom title as character value. #' @param labels If TRUE (default) extracts labels from the attributes, see \link{codebook}. #' @param clean Prepare data by \link{data_clean}. #' @param ... Placeholder to allow calling the method with unused parameters from \link{plot_counts}. #' @return A ggplot object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' plot_counts_one_grouped(data, adopter, sd_gender) #' #' @export #' @importFrom rlang .data plot_counts_one_grouped <- function(data, col, col_group, category = NULL, ordered = NULL, missings = FALSE, prop = "total", numbers = NULL, title = TRUE, labels = TRUE, clean = TRUE, ...) { # 1. Checks check_is_dataframe(data) check_has_column(data, {{ col }}) check_has_column(data, {{ col_group }}) # 2. Clean if (clean) { data <- data_clean(data) } # Swap columns if (prop == "cols") { col <- rlang::enquo(col) col_group <- rlang::enquo(col_group) col_temp <- col col <- col_group col_group <- col_temp #stop("To display column proportions, swap the first and the grouping column. Then set the prop parameter to \"rows\".") } if (!missings) { data <- data %>% tidyr::drop_na({{ col }}, {{ col_group }}) } # 3. Calculate data result <- data %>% dplyr::count({{ col }}, {{ col_group }}) # Detect whether the categories are binary categories <- dplyr::pull(result, {{ col }}) |> unique() |> as.character() if ((length(categories) == 2) && (is.null(category)) && ("TRUE" %in% categories)) { category <- "TRUE" } scale <-dplyr::coalesce(ordered, get_direction(data, {{ col }})) data <- data |> dplyr::mutate(data, "{{ col_group }}" := as.factor({{ col_group }})) if (labels) { result <- labs_replace_values(result, {{ col_group }}, codebook(data, {{ col_group }})) } result <- result %>% dplyr::mutate(item = as.factor({{ col_group }})) |> dplyr::mutate(value = factor({{ col }}, levels = categories)) if ((prop == "rows") || (prop == "cols")) { result <- result %>% dplyr::group_by({{ col_group }}) %>% dplyr::mutate(p = (.data$n / sum(.data$n)) * 100) %>% dplyr::ungroup() } else { result <- result %>% dplyr::mutate(p = (.data$n / sum(.data$n)) * 100) } # Select numbers to print on the bars # ...omit the last category in scales, omit small bars lastcategory <- ifelse(scale > 0, categories[1], categories[length(categories)]) result <- result %>% dplyr::mutate( .values = dplyr::case_when( (is.null(category)) & (scale != 0) & (lastcategory == .data$value) ~ "", .data$p < VLKR_LOWPERCENT ~ "", all(numbers == "n") ~ as.character(.data$n), all(numbers == "p") ~ paste0(round(.data$p, 0), "%"), TRUE ~ paste0(.data$n, "\n", round(.data$p, 0), "%") ) ) # Get title if (title == TRUE) { title <- get_title(data, {{ col }}) } else if (title == FALSE) { title <- NULL } # Get base # TODO: report missing cases base_n <- nrow(data) .plot_bars( result, category = category, scale = scale, numbers = numbers, base = paste0("n=", base_n), title = title ) } #' Output frequencies for multiple variables #' #' TODO: move missings to the end #' #' @keywords internal #' #' @param data A tibble containing item measures #' @param cols Tidyselect item variables (e.g. starts_with...) #' @param category The value FALSE will force to plot all categories. #' A character value will focus a selected category. #' When NULL, in case of boolean values, only the TRUE category is plotted. #' @param ordered Values can be nominal (0) or ordered ascending (1) descending (-1). #' By default (NULL), the ordering is automatically detected. #' An appropriate color scale should be choosen depending on the ordering. #' For unordered values, the default scale is used. #' For ordered values, shaded of the VLKR_FILLGRADIENT option are used. #' @param missings Include missing values (default FALSE) #' @param numbers The values to print on the bars: "n" (frequency), "p" (percentage) or both. #' @param title If TRUE (default) shows a plot title derived from the column labels. #' Disable the title with FALSE or provide a custom title as character value. #' @param labels If TRUE (default) extracts labels from the attributes, see \link{codebook}. #' @param clean Prepare data by \link{data_clean}. #' @param ... Placeholder to allow calling the method with unused parameters from \link{plot_counts}. #' @return A ggplot object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' plot_counts_items(data, starts_with("cg_adoption_")) #' #' @export #' @importFrom rlang .data plot_counts_items <- function(data, cols, category = NULL, ordered = NULL, missings = FALSE, numbers = NULL, title = TRUE, labels = TRUE, clean = TRUE, ...) { # 1. Check parameters check_is_dataframe(data) # 2. Clean if (clean) { data <- data_clean(data) } # Remove missings # TODO: Output a warning if (!missings) { data <- data %>% tidyr::drop_na({{ cols }}) } # 3. Calculate data # n and p result <- data %>% labs_clear({{ cols }}) %>% tidyr::pivot_longer( {{ cols }}, names_to = "item", values_to = "value" ) %>% dplyr::count(dplyr::across(tidyselect::all_of(c("item", "value")))) %>% dplyr::group_by(dplyr::across(tidyselect::all_of("item"))) %>% dplyr::mutate(p = (.data$n / sum(.data$n)) * 100) %>% dplyr::ungroup() %>% dplyr::mutate(value = as.factor(.data$value)) %>% dplyr::arrange(.data$value) # Detect whether the categories are binary categories <- result$value |> unique() |> as.character() if ((length(categories) == 2) && (is.null(category)) && ("TRUE" %in% categories)) { category <- "TRUE" } scale <- dplyr::coalesce(ordered, get_direction(data, {{ cols }})) lastcategory <- ifelse(scale > 0, categories[1], categories[length(categories)]) result <- result %>% dplyr::mutate(value = factor(.data$value, levels = categories)) %>% dplyr::mutate( .values = dplyr::case_when( (is.null(category)) & (scale != 0) & (.data$value == lastcategory) ~ "", p < VLKR_LOWPERCENT ~ "", all(numbers == "n") ~ as.character(n), all(numbers == "p") ~ paste0(round(p, 0), "%"), TRUE ~ paste0(n, "\n", round(p, 0), "%") ) ) # Item labels if (labels) { result <- labs_replace_names(result, "item", codebook(data, {{ cols }})) result <- labs_replace_values(result, "value", codebook(data, {{ cols }})) } # Remove common item prefix prefix <- get_prefix(result$item) if (prefix != "") { result <- dplyr::mutate(result, item = stringr::str_remove(.data$item, prefix)) result <- dplyr::mutate(result, item = ifelse(.data$item == "", prefix, .data$item)) } # Order item levels result <- dplyr::mutate(result, item = factor(.data$item, levels=unique(.data$item))) # Title if (title == TRUE) { title <- get_title(data, {{ cols }}) } else if (title == FALSE) { title <- NULL } # Base # TODO: report missing cases base_n <- nrow(data) .plot_bars( result, category = category, scale = scale, numbers = numbers, base = paste0("n=", base_n, "; multiple responses possible"), title = title ) } #' Plot frequencies of multiple items compared by groups #' #' TODO: implement -> focus one category and show n / p #' #' @keywords internal #' #' @param data A tibble #' @param cols The item columns that hold the values to summarize #' @param col_group The column holding groups to compare #' @param clean Prepare data by \link{data_clean}. #' @param ... Placeholder to allow calling the method with unused parameters from \link{plot_counts}. #' @return A ggplot object #' @importFrom rlang .data plot_counts_items_grouped <- function(data, cols, col_group, clean = TRUE, ...) { stop("Not implemented yet") # 1. Check parameters check_is_dataframe(data) # 2. Clean if (clean) { data <- data_clean(data) } } #' Output a histogram for a single metric variable #' #' @keywords internal #' #' @param data A tibble #' @param col The columns holding metric values #' @param limits The scale limits. Set NULL to extract limits from the label. NOT IMPLEMENTED YET. #' @param negative If FALSE (default), negative values are recoded as missing values. #' @param labels If TRUE (default) extracts labels from the attributes, see \link{codebook}. #' @param title If TRUE (default) shows a plot title derived from the column labels. #' Disable the title with FALSE or provide a custom title as character value. #' @param clean Prepare data by \link{data_clean}. #' @param ... Placeholder to allow calling the method with unused parameters from \link{plot_metrics}. #' @return A ggplot object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' plot_metrics_one(data, sd_age) #' #' @export #' @importFrom rlang .data plot_metrics_one <- function(data, col, limits = NULL, negative = FALSE, title = TRUE, labels = TRUE, clean = TRUE, ...) { # 1. Check parameters check_is_dataframe(data) check_has_column(data, {{ col }}) # 2. Clean if (clean) { data <- data_clean(data) } # Remove negative values # TODO: warn if any negative values were recoded if (!negative) { data <- data |> labs_store() |> dplyr::mutate(dplyr::across({{ col }}, ~ dplyr::if_else(. < 0, NA, .))) |> labs_restore() } # Drop missings # TODO: Report missings data <- tidyr::drop_na(data, {{ col }}) # TODO: make configurable: density, boxplot or histogram pl <- data %>% ggplot2::ggplot(ggplot2::aes({{ col }})) + # geom_histogram(fill=VLKR_FILLCOLOR, bins=20) ggplot2::geom_density(fill = VLKR_FILLCOLOR) + ggplot2::geom_vline(ggplot2::aes(xintercept=mean({{ col }})), color="black") # Get title if (title == TRUE) { title <- get_title(data, {{ col }}) } else if (title == FALSE) { title <- NULL } if (!is.null(title)) { pl <- pl + ggplot2::ggtitle(label = title) + ggplot2::xlab(title) } # Get base # TODO: Report missings base_n <- data %>% nrow() pl <- pl + ggplot2::labs(caption = paste0("n=", base_n)) # Plot styling pl <- pl + ggplot2::theme( axis.title.x = ggplot2::element_blank(), axis.title.y=ggplot2::element_blank(), axis.text.y = ggplot2::element_blank(), # legend.title = element_blank(), plot.caption = ggplot2::element_text(hjust = 0), plot.title.position = "plot", plot.caption.position = "plot" ) # Pass row number and label length to the knit_plot() function # TODO: Don't set rows manually .to_vlkr_plot(pl, rows=4) } #' Output averages for multiple variables #' #' @keywords internal #' #' @param data A tibble containing item measures #' @param col The column holding metric values #' @param col_group The column holding groups to compare #' @param limits The scale limits. Set NULL to extract limits from the labels. NOT IMPLEMENTED YET. #' @param negative If FALSE (default), negative values are recoded as missing values. #' @param title If TRUE (default) shows a plot title derived from the column labels. #' Disable the title with FALSE or provide a custom title as character value. #' @param labels If TRUE (default) extracts labels from the attributes, see \link{codebook}. #' @param clean Prepare data by \link{data_clean}. #' @param ... Placeholder to allow calling the method with unused parameters from \link{plot_metrics}. #' @return A ggplot object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' plot_metrics_one_grouped(data, sd_age, sd_gender) #' #' @export #' @importFrom rlang .data plot_metrics_one_grouped <- function(data, col, col_group, limits = NULL, negative = FALSE, title = TRUE, labels = TRUE, clean = TRUE, ...) { # 1. Check parameters check_is_dataframe(data) check_has_column(data, {{ col }}) check_has_column(data, {{ col_group }}) # 2. Clean if (clean) { data <- data_clean(data) } # Remove negative values # TODO: warn if any negative values were recoded if (!negative) { data <- data |> labs_store() |> dplyr::mutate(dplyr::across({{ col }}, ~ ifelse(. < 0, NA, .))) |> labs_restore() } # Drop missings # TODO: Report missings data <- tidyr::drop_na(data, {{ col }}, {{ col_group }}) pl <- data %>% ggplot2::ggplot(ggplot2::aes(y={{ col_group }}, {{ col }})) + ggplot2::geom_boxplot(fill="transparent", color="darkgray") + ggplot2::stat_summary(fun = mean, geom="point",colour=VLKR_POINTCOLOR, size=4, shape=18) # Set the scale # if (is.null(limits)) { # limits <- get_limits(data, {{ col }}) # } scale <- c() if (labels) { scale <- attr(dplyr::pull(data, {{ col }}), "scale") if (is.null(scale)) { scale <- data %>% codebook({{ col }}) %>% dplyr::distinct(dplyr::across(tidyselect::all_of(c("value_name", "value_label")))) } scale <- prepare_scale(scale) } if (length(scale) > 0) { pl <- pl + ggplot2::scale_x_continuous(labels = ~ label_scale(., scale) ) } else { pl <- pl + ggplot2::scale_x_continuous() } # Add scales, labels and theming pl <- pl + ggplot2::scale_y_discrete(labels = scales::label_wrap(40), limits = rev) + # TODO: set limits #coord_flip(ylim = limits) + ggplot2::theme( axis.title.x = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank(), axis.text.y = ggplot2::element_text(size = 11), legend.title = ggplot2::element_blank(), plot.caption = ggplot2::element_text(hjust = 0), plot.title.position = "plot", plot.caption.position = "plot" ) # # if (!is.null(numbers)) { # pl <- pl + # geom_text( # # aes(label=paste0("⌀", round(m,1))), # aes(label = round(m, 1)), # #position = position_stack(vjust = 0.5), # hjust = -1, # vjust=0.5, # size = 3, # color = "black" # ) # } # Add title if (title == TRUE) { title <- get_title(data, {{ col }}) } else if (title == FALSE) { title <- NULL } if (!is.null(title)) { pl <- pl + ggplot2::ggtitle(label = title) } # Add base # TODO: Report missing values, output range base_n <- nrow(data) pl <- pl + ggplot2::labs(caption = paste0("n=", base_n)) # Maximum label length maxlab <- data %>% dplyr::pull({{col_group}}) %>% stringr::str_length() %>% max(na.rm= TRUE) # Pass row number and label length to the knit_plot() function .to_vlkr_plot(pl, maxlab=maxlab) } #' Output averages for multiple variables #' #' @keywords internal #' #' @param data A tibble containing item measures #' @param cols Tidyselect item variables (e.g. starts_with...) #' @param limits The scale limits. Set NULL to extract limits from the labels. NOT IMPLEMENTED YET. #' @param negative If FALSE (default), negative values are recoded as missing values. #' @param title If TRUE (default) shows a plot title derived from the column labels. #' Disable the title with FALSE or provide a custom title as character value. #' @param labels If TRUE (default) extracts labels from the attributes, see \link{codebook}. #' @param clean Prepare data by \link{data_clean}. #' @param ... Placeholder to allow calling the method with unused parameters from \link{plot_metrics}. #' @return A ggplot object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' plot_metrics_items(data, starts_with("cg_adoption_")) #' #' @export plot_metrics_items <- function(data, cols, limits = NULL, negative = FALSE, title = TRUE, labels = TRUE, clean = TRUE, ...) { # 1. Check parameters check_is_dataframe(data) # 2. Clean if (clean) { data <- data_clean(data) } # Remove negative values # TODO: warn if any negative values were recoded # TODO: Call prepare in every function and replace there, same for missings if (!negative) { data <- data %>% labs_store() %>% dplyr::mutate(dplyr::across({{ cols }}, ~ ifelse(. < 0, NA, .))) %>% labs_restore() } # Drop missings # TODO: Report missings data <- tidyr::drop_na(data, {{ cols }}) # Pivot items result <- data %>% labs_clear({{ cols }}) %>% tidyr::pivot_longer( {{ cols }}, names_to = "item", values_to = "value" ) # Replace item labels if (labels) { result <- labs_replace_names(result, "item", codebook(data, {{ cols }})) } # Remove common item prefix and title # TODO: remove common postfix prefix <- get_prefix(result$item) if (prefix != "") { result <- dplyr::mutate(result, item = stringr::str_remove(.data$item, stringr::fixed(prefix))) result <- dplyr::mutate(result, item = ifelse(.data$item == "", prefix, .data$item)) } # Order item levels result <- dplyr::mutate(result, item = factor(.data$item, levels=unique(.data$item))) # Create plot pl <- result %>% ggplot2::ggplot(ggplot2::aes(y=.data$item, .data$value)) + ggplot2::geom_boxplot(fill="transparent", color="darkgray") + ggplot2::stat_summary(fun = mean, geom="point",colour=VLKR_POINTCOLOR, size=4, shape=18) # Add scale labels scale <- c() if (labels) { scale <- data %>% codebook({{ cols }}) %>% dplyr::distinct(dplyr::across(tidyselect::all_of(c("value_name", "value_label")))) %>% prepare_scale() } if (length(scale) > 0) { pl <- pl + ggplot2::scale_x_continuous(labels = ~ label_scale(., scale) ) } else { pl <- pl + ggplot2::scale_x_continuous() } # Add scales, labels and theming pl <- pl + ggplot2::scale_y_discrete(labels = scales::label_wrap(40), limits=rev) + # TODO: set limits #coord_flip(ylim = limits) + ggplot2::theme( axis.title.x = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank(), axis.text.y = ggplot2::element_text(size = 11), legend.title = ggplot2::element_blank(), plot.caption = ggplot2::element_text(hjust = 0), plot.title.position = "plot", plot.caption.position = "plot" ) # Add title if (title == TRUE) { title <- get_title(data, {{ cols }}) } else if (title == FALSE) { title <- NULL } if (!is.null(title)) { pl <- pl + ggplot2::ggtitle(label = title) } # Add base # TODO: report missings base_n <- nrow(data) pl <- pl + ggplot2::labs(caption = paste0("n=", base_n, "; multiple responses possible")) # Maximum label length maxlab <- result %>% dplyr::pull(.data$item) %>% stringr::str_length() %>% max(na.rm = TRUE) # Pass row number and label length to the knit_plot() function .to_vlkr_plot(pl, maxlab=maxlab) } #' Output averages for multiple variables compared by a grouping variable #' #' @keywords internal #' #' @param data A tibble containing item measures #' @param cols Tidyselect item variables (e.g. starts_with...) #' @param col_group The column holding groups to compare #' @param limits The scale limits. Set NULL to extract limits from the labels. NOT IMPLEMENTED YET. #' @param negative If FALSE (default), negative values are recoded as missing values. #' @param title If TRUE (default) shows a plot title derived from the column labels. #' Disable the title with FALSE or provide a custom title as character value. #' @param labels If TRUE (default) extracts labels from the attributes, see \link{codebook}. #' @param clean Prepare data by \link{data_clean}. #' @param ... Placeholder to allow calling the method with unused parameters from \link{plot_metrics}. #' @return A ggplot object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' plot_metrics_items_grouped(data, starts_with("cg_adoption_"), sd_gender) #' #' @export #' @importFrom rlang .data plot_metrics_items_grouped <- function(data, cols, col_group, limits = NULL, negative = FALSE, title = TRUE, labels = TRUE, clean = TRUE, ...) { # 1. Check parameters check_is_dataframe(data) check_has_column(data, {{ col_group }}) # 2. Clean if (clean) { data <- data_clean(data) } # TODO: warn if any negative values were recoded if (!negative) { data <- dplyr::mutate(data, dplyr::across({{ cols }}, ~ dplyr::if_else(. < 0, NA, .))) } # Drop missings # TODO: Report missings data <- tidyr::drop_na(data, {{ cols }}, {{ col_group }}) # 3. Calculate # Get positions of group cols col_group <- tidyselect::eval_select(expr = rlang::enquo(col_group), data = data) # Grouped means result <- map( col_group, function(col) { col <- names(data)[col] data %>% dplyr::filter(!is.na(!!sym(col))) %>% dplyr::group_by(!!sym(col)) %>% dplyr::select(!!sym(col), {{ cols }}) %>% skim_metrics() %>% dplyr::ungroup() %>% dplyr::select(item = "skim_variable", group = !!sym(col), "numeric.mean") %>% tidyr::drop_na() } ) %>% purrr::reduce( dplyr::bind_rows ) if (is.null(limits)) { limits <- get_limits(data, {{ cols }}) } # Replace item labels if (labels) { result <- labs_replace_names(result, "item", codebook(data, {{ cols }})) } # Remove common item prefix prefix <- get_prefix(result$item) if (prefix != "") { result <- dplyr::mutate(result, item = stringr::str_remove(.data$item, prefix)) result <- dplyr::mutate(result, item = ifelse(.data$item == "", prefix, .data$item)) } # Order item levels result <- dplyr::mutate(result, item = factor(.data$item, levels=unique(.data$item))) # print(result) # class(result) <- setdiff(class(result),"skim_df") pl <- result %>% ggplot2::ggplot(ggplot2::aes( .data$item, y = .data$numeric.mean, color = .data$group, group=.data$group) ) + ggplot2::geom_line() + ggplot2::geom_point(size=3, shape=18) #geom_col(position = "dodge") # Set the scale # TODO: get from attributes scale <- data %>% codebook({{ cols }}) %>% dplyr::distinct(dplyr::across(tidyselect::all_of(c("value_name", "value_label")))) %>% prepare_scale() if (length(scale) > 0) { pl <- pl + ggplot2::scale_y_continuous(labels = ~ label_scale(., scale) ) } else { pl <- pl + ggplot2::scale_y_continuous() } # Add scales, labels and theming pl <- pl + ggplot2::scale_x_discrete(labels = scales::label_wrap(40), limits = rev) + ggplot2::scale_color_discrete(labels = function(x) stringr::str_wrap(x, width = 40)) + ggplot2::ylab("Mean values") + ggplot2::coord_flip(ylim = limits) + ggplot2::theme( axis.title.x = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank(), axis.text.y = ggplot2::element_text(size = 11), legend.title = ggplot2::element_blank(), plot.caption = ggplot2::element_text(hjust = 0), plot.title.position = "plot", plot.caption.position = "plot" ) # Add title if (title == TRUE) { title <- trim_label(prefix) } else if (title == FALSE) { title <- NULL } if (!is.null(title)) { pl <- pl + ggplot2::ggtitle(label = title) } # Add base # TODO: Report missings base_n <- nrow(data) pl <- pl + ggplot2::labs(caption = paste0("n=", base_n, "; multiple responses possible")) # Convert to vlkr_plot .to_vlkr_plot(pl) } #' Helper function: plot grouped bar chart #' #' @keywords internal #' #' @param data Dataframe with the columns Item, value, p, n #' @param category Category for filtering the dataframe #' @param scale Direction of the scale: 0 = no direction for categories, #' -1 = descending or 1 = ascending values. #' @param numbers The values to print on the bars: "n" (frequency), "p" (percentage) or both. #' @param title The plot title as character or NULL #' @param base The plot base as character or NULL. #' @return A ggplot object #' @importFrom rlang .data .plot_bars <- function(data, category = NULL, scale = NULL, numbers = NULL, base = NULL, title = NULL) { if (!is.null(category)) { data <- dplyr::filter(data, .data$value == category) } if (scale <= 0) { data <- data %>% dplyr::mutate(value = forcats::fct_rev(.data$value)) } pl <- data %>% ggplot2::ggplot(ggplot2::aes(.data$item, y = .data$p / 100, fill = .data$value, group = .data$value)) + ggplot2::geom_col() + ggplot2::scale_y_continuous(labels = scales::percent) + ggplot2::scale_x_discrete(labels = scales::label_wrap(40), limits = rev) + ggplot2::ylab("Share in percent") + ggplot2::coord_flip() + ggplot2::theme( axis.title.x = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank(), axis.text.y = ggplot2::element_text(size = 11), legend.title = ggplot2::element_blank(), plot.caption = ggplot2::element_text(hjust = 0), plot.title.position = "plot", plot.caption.position = "plot" ) # Select scales: # - Simplify binary plots # - Generate a color scale for ordinal scales from VLKR_FILLGRADIENT # - Use the default color for other cases if (!is.null(category)) { pl <- pl + ggplot2::scale_fill_manual( values = c(VLKR_FILLCOLOR), guide = ggplot2::guide_legend(reverse = TRUE) ) + ggplot2::theme( legend.position = ifelse(category == "TRUE" | category == TRUE, "none","bottom"), legend.justification = "left" ) } else if ((scale > 0) || (scale < 0)) { colors <- scales::gradient_n_pal(VLKR_FILLGRADIENT)( seq(0,1,length.out=length(levels(data$value))) ) pl <- pl + ggplot2::scale_fill_manual( values = colors, guide = ggplot2::guide_legend(reverse = TRUE) ) } else { pl <- pl + ggplot2::scale_fill_discrete( guide = ggplot2::guide_legend(reverse = TRUE) ) } # Add numbers if (!is.null(numbers)) { pl <- pl + ggplot2::geom_text(ggplot2::aes(label = .data$.values), position = ggplot2::position_stack(vjust = 0.5), size = 3, color = "white") } # Add title if (!is.null(title)) { pl <- pl + ggplot2::ggtitle(label = title) } # Add base if (!is.null(base)) { pl <- pl + ggplot2::labs(caption = base) } # Convert to vlkr_plot .to_vlkr_plot(pl) } #' Add the volker class and options #' #' @keywords internal #' #' @param pl A ggplot object #' @param rows The number of items on the vertical axis. Will be automatically determined when NULL. #' For stacked bar charts, don't forget to set the group parameter, otherwise it won't work #' @param maxlab The character length of the longest label to be plotted. Will be automatically determined when NULL. #' on the vertical axis #' @return A ggplot object with vlkr_plt class .to_vlkr_plot <- function(pl, rows = NULL, maxlab = NULL) { class(pl) <- c("vlkr_plt", class(pl)) plot_data <- ggplot2::ggplot_build(pl) if (is.null(rows)) { if ("CoordFlip" %in% class(pl$coordinates)) { labels <- plot_data$layout$panel_scales_x[[1]]$range$range } else { labels <- plot_data$layout$panel_scales_y[[1]]$range$range } legend <- unique(plot_data$data[[1]]$group) rows <- max(length(labels), (length(legend) / 3) * 2) } if (is.null(maxlab)) { labels <- plot_data$layout$panel_scales_x[[1]]$range$range #labels <- layer_scales(pl)$x$range$range #labels <- pl$data[[1]] maxlab <- max(stringr::str_length(labels), na.rm= TRUE) } attr(pl, "vlkr_options") <- list( rows = rows, maxlab = maxlab ) pl } #' Knit volker plots #' #' Automatically calculates the plot height from #' chunk options and volker options. #' #' Presumptions: #' - a screen resolution of 72dpi #' - a default plot width of 7 inches = 504px #' - a default page width of 700px (vignette) or 910px (report) #' - an optimal bar height of 40px for 910px wide plots. i.e. a ratio of 0.04 #' - an offset of one bar above and one bar below #' #' @keywords internal #' #' @param pl A ggplot object with vlkr_options. #' The vlk_options are added by .to_vlkr_plot() #' and provide information about the number of vertical items (rows) #' and the maximum #' @return Character string containing a html image tag, including the base64 encoded image knit_plot <- function(pl) { # Get knitr and volkr chunk options chunk_options <- knitr::opts_chunk$get() plot_options <- attr(pl, "vlkr_options") fig_width <- chunk_options$fig.width * 72 fig_height <- chunk_options$fig.height * 72 fig_dpi <- VLKR_PLOT_DPI fig_scale <- fig_dpi / VLKR_PLOT_SCALE # TODO: GET PAGE WIDTH FROM SOMEWHERE # page_width <- dplyr::coalesce(chunk_options$page.width, 1) # Calculate plot height if (!is.null(plot_options[["rows"]])) { fig_width <- VLKR_PLOT_WIDTH # TODO: make configurable px_perline <- VLKR_PLOT_PXPERLINE # TODO: make configurable # Buffer above and below the diagram px_offset <- VLKR_PLOT_OFFSETROWS * px_perline if (!is.null(pl$labels$title)) { px_offset <- px_offset + VLKR_PLOT_TITLEROWS * px_perline } rows <- plot_options[["rows"]] lines_wrap <- dplyr::coalesce(plot_options[["labwrap"]], VLKR_PLOT_LABELWRAP) lines_perrow <- (dplyr::coalesce(plot_options[["maxlab"]], 1) %/% lines_wrap) + 2 fig_height <- (rows * lines_perrow * px_perline) + px_offset } # if (length(dev.list()) > 0) { # dev.off() # } pngfile <- tempfile(fileext = ".png", tmpdir = chunk_options$cache.path) suppressMessages(ggplot2::ggsave( pngfile, pl, # type = "cairo-png", # antialias = "subpixel", width = fig_width, height = fig_height, units = "px", dpi = fig_dpi, scale = fig_scale, dev = "png" )) #dev.off() base64_string <- base64enc::base64encode(pngfile) paste0('<img src="data:image/png;base64,', base64_string, '" width="100%">') } #' Printing method for volker plots #' #' @keywords internal #' #' @param x The volker plot #' @param ... Further parameters passed to print() #' @return No return value #' @examples #' library(volker) #' data <- volker::chatgpt #' #' pl <- plot_metrics(data, sd_age) #' print(pl) #' #' @export print.vlkr_plt <- function(x, ...) { if (knitr::is_html_output()) { # TODO: leads to endless recursion # x <- knit_plot(x) # x <- knitr::asis_output(x) # knitr::knit_print(x) NextMethod() } else { NextMethod() } } #' @rdname print.vlkr_plt #' @method plot vlkr_plt #' @keywords internal #' @export plot.vlkr_plt <- print.vlkr_plt
/scratch/gouwar.j/cran-all/cranData/volker/R/plots.R
#' Create table and plot for metric variables #' #' Depending on your column selection, different types of plots and tables are generated. #' See \link{plot_metrics} and \link{tab_metrics}. #' #' For item batteries, an index is calculated and reported. #' When used in combination with the Markdown-template "html_report", #' the different parts of the report are grouped under a tabsheet selector. #' #' @param data A data frame #' @param cols A tidy column selection, #' e.g. a single column (without quotes) #' or multiple columns selected by methods such as starts_with(). #' @param col_group Optional, a grouping column (without quotes). #' @param ... Parameters passed to the plot and tab functions. #' @param index When the cols contain items on a metric scale #' (as determined by \link{get_direction}), #' an index will be calculated using the 'psych' package. #' Set to FALSE to suppress index generation. #' @param title A character providing the heading or TRUE (default) to output a heading. #' Classes for tabset pills will be added. #' @param close Whether to close the last tab (default value TRUE) or to keep it open. #' Keep it open to add further custom tabs by adding headers on the fifth level #' in Markdown (e.g. ##### Method) #' @param clean Prepare data by \link{data_clean}. #' @return A volker report object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' report_metrics(data, sd_age) #' #' @export report_metrics <- function(data, cols, col_group = NULL, ..., index = TRUE, title = TRUE, close = TRUE, clean = TRUE) { if (clean) { data <- data_clean(data) } chunks <- list() # Add title if (!is.character(title) && (title == TRUE)) { title <- get_title(data, {{ cols }}) } else if (!is.character(title)) { title <- "" } if (is.character(title) && knitr::is_html_output()) { chunks <- .add_to_vlkr_rprt(paste0("\n#### ", title, " {.tabset .tabset-pills} \n"), chunks) plot_title <- FALSE } else { plot_title <- TRUE } # Add Plot chunks <- plot_metrics(data, {{ cols}}, {{ col_group }}, clean=clean, ..., title = plot_title) %>% .add_to_vlkr_rprt(chunks, "Plot") # Add table chunks <- tab_metrics(data, {{ cols}}, {{ col_group }}, clean=clean, ...) %>% .add_to_vlkr_rprt(chunks, "Table") # Add index if (index) { idx <- .report_idx(data, {{ cols}}, {{ col_group }}, title = plot_title) chunks <- append(chunks,idx) } # Close tabs if (close) { if (knitr::is_html_output()) { chunks <- .add_to_vlkr_rprt(paste0("\n##### {-} \n"), chunks) } if (is.character(title) && knitr::is_html_output()) { chunks <- .add_to_vlkr_rprt(paste0("\n#### {-} \n"), chunks) } } .to_vlkr_rprt(chunks) } #' Create table and plot for categorical variables #' #' Depending on your column selection, different types of plots and tables are generated. #' See \link{plot_counts} and \link{tab_counts}. #' #' For item batteries, an index is calculated and reported. #' When used in combination with the Markdown-template "html_report", #' the different parts of the report are grouped under a tabsheet selector. #' #' @param data A data frame #' @param cols A tidy column selection, #' e.g. a single column (without quotes) #' or multiple columns selected by methods such as starts_with(). #' @param col_group Optional, a grouping column (without quotes). #' @param index When the cols contain items on a metric scale #' (as determined by \link{get_direction}), #' an index will be calculated using the 'psych' package. #' Set to FALSE to suppress index generation. #' @param numbers The numbers to print on the bars: "n" (frequency), "p" (percentage) or both. #' Set to NULL to remove numbers. #' @param title A character providing the heading or TRUE (default) to output a heading. #' Classes for tabset pills will be added. #' @param close Whether to close the last tab (default value TRUE) or to keep it open. #' Keep it open to add further custom tabs by adding headers on the fifth level #' in Markdown (e.g. ##### Method) #' @param clean Prepare data by \link{data_clean}. #' @param ... Parameters passed to the plot and tab functions. #' @return A volker report object #' @examples #' library(volker) #' data <- volker::chatgpt #' #' report_counts(data, sd_gender) #' #' @export report_counts <- function(data, cols, col_group = NULL, index = TRUE, numbers = NULL, title = TRUE, close = TRUE, clean = TRUE, ...) { if (clean) { data <- data_clean(data) } chunks <- list() # Add title if (knitr::is_html_output()) { if (!is.character(title) && (title == TRUE)) { title <- get_title(data, {{ cols }}) } else if (!is.character(title)) { title <- "" } chunks <- .add_to_vlkr_rprt(paste0("\n#### ", title, " {.tabset .tabset-pills} \n"), chunks) plot_title <- FALSE } else { plot_title <- title } # Add Plot chunks <- plot_counts(data, {{ cols }}, {{ col_group }}, ..., title = plot_title, numbers=numbers, clean=clean) %>% .add_to_vlkr_rprt(chunks, "Plot") # Add table chunks <- tab_counts(data, {{ cols }}, {{ col_group }}, clean=clean, ...) %>% .add_to_vlkr_rprt(chunks, "Table") # Add index if (index) { idx <- .report_idx(data, {{ cols }}, {{ col_group }}, title = plot_title) chunks <- append(chunks,idx) } # Close tabs if (close) { if (knitr::is_html_output()) { chunks <- .add_to_vlkr_rprt(paste0("\n##### {-} \n"), chunks) } if (is.character(title) && knitr::is_html_output()) { chunks <- .add_to_vlkr_rprt(paste0("\n#### {-} \n"), chunks) } } .to_vlkr_rprt(chunks) } #' Generate an index table and plot #' #' @keywords internal #' #' @param data A data frame #' @param cols A tidy column selection, #' e.g. a single column (without quotes) #' or multiple columns selected by methods such as starts_with(). #' @param col_group Optional, a grouping column (without quotes). #' @param title Add a plot title (default = TRUE) #' @return A list containing a table and a plot volker report chunk .report_idx <- function(data, cols, col_group, title = TRUE) { chunks <- list() cols_eval <- tidyselect::eval_select(expr = enquo(cols), data = data) is_items <- length(cols_eval) > 1 is_scale <- get_direction(data, {{ cols }}, FALSE) if (is_items && (is_scale != 0)) { idx <- idx_add(data, {{ cols }}, newcol = ".idx") idx_name <- setdiff(colnames(idx), colnames(data)) if (length(idx_name) > 0) { chunks <- idx %>% plot_metrics(!!rlang::sym(idx_name), {{ col_group }}, title = title) %>% .add_to_vlkr_rprt(chunks, "Index: Plot") chunks <- idx %>% tab_metrics(!!rlang::sym(idx_name), {{ col_group }}) %>% .add_to_vlkr_rprt(chunks, "Index: Table") } } chunks } #' Add the vlkr_rprt class to an object #' #' Adding the class makes sure the appropriate printing function #' is applied in markdown reports. #' #' @keywords internal #' #' @param chunks A list of character strings #' @return A volker report object: List of character strings with the vlkr_rprt class #' containing the parts of the report .to_vlkr_rprt <- function(chunks) { class(chunks) <- c("vlkr_rprt", setdiff(class(chunks),"vlkr_rprt")) chunks } #' Add an object to the report list #' #' @keywords internal #' #' @param obj A new chunk (volker table, volker plot or character value) #' @param chunks The current report list #' @param tab A tabsheet name or NULL #' @return A volker report object .add_to_vlkr_rprt <- function(obj, chunks, tab = NULL) { if (knitr::is_html_output()) { # Tab if (!is.null(tab)) { tab <- paste0("\n##### ", tab, " \n") chunks <- .add_to_vlkr_rprt(tab, chunks) } # Objects if (inherits(obj, "vlkr_tbl")) { newchunk <- knit_table(obj) } else if (inherits(obj, "vlkr_plt")) { newchunk <- knit_plot(obj) } else if (is.character(obj)) { newchunk <- obj } else { warning("Could not determine the volker report chunk type") } chunks <- append(chunks, newchunk) } else { if (!is.null(tab)) { attr(obj,"comment") <- tab } chunks <- append(chunks, list(obj)) } .to_vlkr_rprt(chunks) } #' Printing method for volker reports. #' #' @keywords internal #' #' @param x The volker report object #' @param ... Further parameters passed to print #' @importFrom rlang .data #' @return No return value #' @examples #' library(volker) #' data <- volker::chatgpt #' #' rp <- report_metrics(data, sd_age) #' print(rp) #' #' @export print.vlkr_rprt <- function(x, ...) { if (knitr::is_html_output()) { x %>% unlist() %>% paste0(collapse = "\n") %>% knitr::asis_output() %>% knitr::knit_print() } else { for (part in x) { print(part, ...) } } } #' Volker style HTML document format #' #' Based on the standard theme, tweaks the pill navigation #' to switch between tables and plots. #' To use the format, in the header of your Markdown document, #' set `output: volker::html_report`. #' #' @param ... Additional arguments passed to html_document #' @return R Markdown output format #' @examples #' \dontrun{ #' # Add `volker::html_report` to the output options of your Markdown document: #' # #' # ``` #' # --- #' # title: "How to create reports?" #' # output: volker::html_report #' # --- #' # ``` #' } #' @export html_report <- function(...) { cssfile <- paste0(system.file("extdata", package = "volker"),"/styles.css") rmarkdown::html_document( css = cssfile, ... ) }
/scratch/gouwar.j/cran-all/cranData/volker/R/report.R