content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
---
title: "Using virustotal"
author: "Gaurav Sood"
date: "`r Sys.Date()`"
vignette: >
%\VignetteIndexEntry{Using virustotal}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
## Using virustotal
### Installation
To get the current development version from GitHub:
```{r, eval=F, install}
#library(devtools)
install_github("soodoku/virustotal")
```
#### Load up the lib:
```{r, eval=F, load}
library(virustotal)
```
#### Authentication
Start by getting the API key from [https://www.virustotal.com/](https://www.virustotal.com/). Next, set it:
```{r, eval=F, api_key}
set_key("your_key")
```
#### Get domain report
Get report on a domain, including passive DNS:
```{r, eval=F, domain}
domain_report("http://www.google.com")$categories
```
```
## [[1]]
## [1] "searchengines"
```
#### Scan URL
```{r, eval=F, scan_url}
scan_url("http://www.google.com")
```
```
## permalink resource
## 1 https://www.virustotal.com/url/dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf/analysis/1464817664/ http://www.google.com/
```
#### Get URL report
Get report on a domain, including URL:
```{r, eval=F, url}
head(url_report("http://www.google.com")[, 1:2], 10)
```
```
## scan_id resource
## 1 dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf-1464816996 http://www.google.com
## 2 dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf-1464816996 http://www.google.com
## 3 dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf-1464816996 http://www.google.com
## 4 dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf-1464816996 http://www.google.com
## 5 dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf-1464816996 http://www.google.com
## 6 dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf-1464816996 http://www.google.com
## 7 dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf-1464816996 http://www.google.com
## 8 dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf-1464816996 http://www.google.com
## 9 dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf-1464816996 http://www.google.com
## 10 dd014af5ed6b38d9130e3f466f850e46d21b951199d53a18ef29ee9341614eaf-1464816996 http://www.google.com
```
#### Get IP report
```{r, eval=F, ip}
ip_report("8.8.8.8")$country
```
```
## [1] "US"
```
#### Get File Report
```{r, eval=F, file}
head(file_report("99017f6eebbac24f351415dd410d522d")[,1:2], 10)
```
```
scans scan_id
## Bkav FALSE, 1.3.0.8042, 20160601 52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c-1464797947
## TotalDefense TRUE, 37.1.62.1, Win32/ASuspect.HDBBD, 20160601 52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c-1464797947
## MicroWorld-eScan TRUE, 12.0.250.0, Generic.Malware.V!w.7232B058, 20160601 52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c-1464797947
## nProtect TRUE, 2016-06-01.01, Trojan/W32.Small.28672.BJA, 20160601 52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c-1464797947
## CMC TRUE, 1.1.0.977, Trojan.Win32.VB!O, 20160530 52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c-1464797947
## CAT-QuickHeal TRUE, 14.00, Trojan.Comame.r3, 20160601 52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c-1464797947
## ALYac TRUE, 1.0.1.9, Generic.Malware.V!w.7232B058, 20160601 52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c-1464797947
## Malwarebytes TRUE, 2.1.1.1115, Trojan.Qhost, 20160601 52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c-1464797947
## Zillya TRUE, 2.0.0.2901, Trojan.VB.Win32.33493, 20160531 52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c-1464797947
## SUPERAntiSpyware FALSE, 5.6.0.1032, 20160601 52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c-1464797947
```
#### Scan File
```{r, eval=F, scan_file}
scan_file("using_virustotal.Rmd")[,1:2]
```
```
## scan_id sha1
## 1 a9e60cd4d1e3ea00a78f7e92b77f250b26297d79e387e30916de3973a03b28a0-1464822937 303e723fd79416c3a8f3ac8247f82ed2f22e635d
```
#### Rescan File
```{r, eval=F, rescan_file}
rescan_file(hash='99017f6eebbac24f351415dd410d522d')[,1:2]
```
```
## permalink response_code
## 1 https://www.virustotal.com/file/52d3df0ed60c46f336c131bf2ca454f73bafdc4b04dfa2aea80746f5ba9e6d1c/analysis/1464817836/ 1
```
|
/scratch/gouwar.j/cran-all/cranData/virustotal/vignettes/using_virustotal.Rmd
|
#' Use fontAwesome icons in visNetwork \code{graph}
#'
#' Add \href{https://fontawesome.com}{Font-Awesome} for styling
#' our \code{graph} with beautiful, professional icons. Please note
#' that you'll already have these icons if using Shiny.
#' Can also use \link{addIonicons}
#'
#' @param graph : a visNetwork object
#' @param name : name of dependency
#' @param version : fontawesome version. "4.7.0" (default) or "5.13.0"
#'
#' @return \code{graph} htmlwidget with Font-Awesome dependencies attached.
#'
#' @examples
#'
#' # use fontAwesome icons using groups or nodes options
#' # font-awesome is not part of dependencies. use addFontAwesome() if needed.
#' # Versions in package (and compatible with vis.js) : 4.7.0 & 5.13.0
#' # https://fontawesome.com/v4.7.0/
#' # https://fontawesome.com/
#' # cheatsheet available in package:
#' # system.file("fontAwesome/Font_Awesome_Cheatsheet_4_7_0.pdf", package = "visNetwork")
#'
#' # definition in groups
#' nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
#' edges <- data.frame(from = c(1,2), to = c(2,3))
#'
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", shape = "icon", icon = list(code = "f0c0", size = 75)) %>%
#' visGroups(groupname = "B", shape = "icon", icon = list(code = "f007", color = "red")) %>%
#' addFontAwesome(version = "4.7.0")
#'
#' # use 5.13.0
#' # set face = "'Font Awesome 5 Free'"
#' # weight is automatically set to "bold"
#' nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
#' edges <- data.frame(from = c(1,2), to = c(2,3))
#'
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", shape = "icon",
#' icon = list(face = "'Font Awesome 5 Free'", code = "f0c0", size = 75)) %>%
#' visGroups(groupname = "B", shape = "icon",
#' icon = list(face = "'Font Awesome 5 Free'", code = "f007", color = "red")) %>%
#' addFontAwesome(version = "5.13.0")
#'
#' # definition in nodes
#' nodes <- data.frame(id = 1:3, shape = "icon", icon.face = 'FontAwesome',
#' icon.code = "f0c0")
#' edges <- data.frame(from = c(1,2), to = c(1,3))
#'
#' visNetwork(nodes, edges) %>%
#' addFontAwesome()
#'
#' # using shinydashboard : change name if needed
#' visNetwork(nodes, edges) %>%
#' addFontAwesome(name = "font-awesome-visNetwork")
#'
#' @import htmltools
#'
#' @export
addFontAwesome <- function(graph, name = "font-awesome", version = c("4.7.0", "5.13.0")){
if(!inherits(graph,"htmlwidget")){
stop("graph should be a htmlwidget.", call.=F)
}
version <- match.arg(version)
font_dep <- htmltools::htmlDependency(
name = name,
version = version,
src = c(file=system.file(paste0("htmlwidgets/lib/fontawesome_", version), package="visNetwork")),
stylesheet = switch(version,
"4.7.0" = "css/font-awesome.min.css",
"5.13.0" = "css/all.min.css"
)
)
if(length(graph$dependencies) == 0){
graph$dependencies = list()
}
graph$dependencies[[length(graph$dependencies)+1]] <- font_dep
graph$x$iconsRedraw <- TRUE
graph
}
#' Use Ionicons in visNetwork \code{graph}
#'
#' Add \href{https://ionic.io/ionicons}{Ionicons} for styling
#' our \code{graph} with beautiful, professional icons.
#' Can also use \link{addFontAwesome}
#'
#' @param graph : a visNetwork object
#' @param name : name of dependency
#'
#' @return \code{graph} htmlwidget with Ionicons dependencies attached.
#'
#' @examples
#'
#' nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
#' edges <- data.frame(from = c(1,2), to = c(2,3))
#'
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", shape = "icon",
#' icon = list(face ='Ionicons', code = "f101", size = 75)) %>%
#' visGroups(groupname = "B", shape = "icon",
#' icon = list(face ='Ionicons', code = "f100", color = "red")) %>%
#' addIonicons()
#'
#' @import htmltools
#'
#' @export
addIonicons <- function(graph, name = "ionicons"){
if(!inherits(graph,"htmlwidget")){
stop("graph should be a htmlwidget.", call.=F)
}
font_dep <- htmltools::htmlDependency(
name = name,
version = "2.0.1",
src = c(file=system.file("htmlwidgets/lib/ionicons", package="visNetwork")),
stylesheet = "css/ionicons.min.css"
)
if(length(graph$dependencies) == 0){
graph$dependencies = list()
}
graph$dependencies[[length(graph$dependencies)+1]] <- font_dep
graph$x$iconsRedraw <- TRUE
graph
}
#' Add libraries dependencies used in export \link{visExport}
#'
#'
#' @param graph : a visNetwork object
#' @param pdf : boolean. Add jsPDF or not ?
#'
#' @return \code{graph} htmlwidget with dependencies attached.
#'
#' @import htmltools
#'
#' @export
#
addExport <- function(graph, pdf = TRUE){
if(!inherits(graph,"htmlwidget")){
stop("graph should be a htmlwidget.", call.=F)
}
fileSaver_dep <- htmltools::htmlDependency(
name = "FileSaver",
version = "1.1.20151003",
src = c(file=system.file("htmlwidgets/lib/export/FileSaver", package="visNetwork")),
script = "FileSaver.min.js"
)
Blob_dep <- htmltools::htmlDependency(
name = "Blob",
version = "1.0",
src = c(file=system.file("htmlwidgets/lib/export/Blob", package="visNetwork")),
script = "Blob.js"
)
canvastoBlob_dep <- htmltools::htmlDependency(
name = "canvas-toBlob",
version = "1.0",
src = c(file=system.file("htmlwidgets/lib/export/canvas-toBlob", package="visNetwork")),
script = "canvas-toBlob.js"
)
html2canvas_dep <- htmltools::htmlDependency(
name = "html2canvas",
version = "0.5.0",
src = c(file=system.file("htmlwidgets/lib/export/html2canvas", package="visNetwork")),
script = "html2canvas.js"
)
if(length(graph$dependencies) == 0){
graph$dependencies = list()
}
graph$dependencies[[length(graph$dependencies)+1]] <- fileSaver_dep
graph$dependencies[[length(graph$dependencies)+1]] <- Blob_dep
graph$dependencies[[length(graph$dependencies)+1]] <- canvastoBlob_dep
graph$dependencies[[length(graph$dependencies)+1]] <- html2canvas_dep
if(pdf){
jspdf_dep <- htmltools::htmlDependency(
name = "jspdf",
version = "1.3.2",
src = c(file=system.file("htmlwidgets/lib/export/jsPDF", package="visNetwork")),
script = "jspdf.debug.js"
)
graph$dependencies[[length(graph$dependencies)+1]] <- jspdf_dep
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/dependencies.R
|
mergeLists <- function (base_list, overlay_list, recursive = TRUE) {
if (length(base_list) == 0)
overlay_list
else if (length(overlay_list) == 0)
base_list
else {
merged_list <- base_list
for (name in names(overlay_list)) {
base <- base_list[[name]]
overlay <- overlay_list[[name]]
if (is.list(base) && is.list(overlay) && recursive)
merged_list[[name]] <- mergeLists(base, overlay)
else {
merged_list[[name]] <- NULL
merged_list <- append(merged_list,
overlay_list[which(names(overlay_list) %in% name)])
}
}
merged_list
}
}
toArrayList <- function(obj, names = TRUE){
value = lapply(1:nrow(obj), function(i) {
res <- as.list(obj[i, , drop = FALSE])
if (!names) names(res) <- NULL
res
})
names(value) <- NULL;
value
}
#' Export magrittr function
#'
#' Export magrittr function
#'
#' @importFrom magrittr %>%
#' @name %>%
#' @export
#' @rdname visNetwork-exports
NULL
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/utils.R
|
#' Network visualization clustering options - outliers
#'
#' Network visualization clustering options - outliers
#'
#' @param graph : a visNetwork object
#' @param clusterFactor : Number, from 0 to 1. 0.9 by default
#' @param stabilize : Boolean, default to false
#'
#' @examples
#'
#' nodes <- data.frame(id = 1:10)
#' edges <- data.frame(from = c(1,1,10,2,6,7,8,9,10),
#' to = c(2,3,4,5,2,5,6,7,9))
#'
#' visNetwork(nodes, edges) %>%
#' visClusteringOutliers(1)
#'
#'
#' @export
visClusteringOutliers <- function(graph, clusterFactor = 0.9, stabilize = FALSE){
if(any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visClusteringOutliers with visNetworkProxy object")
}
if(!any(class(graph) %in% "visNetwork")){
stop("graph must be a visNetwork object")
}
clusteringOutliers <- list(clusterFactor = clusterFactor, stabilize = stabilize)
graph$x$clusteringOutliers <- mergeLists(graph$x$clusteringOutliers, clusteringOutliers)
graph
}
#' Network visualization clustering options - by color
#'
#' Network visualization clustering options - by color.
#'
#' @param graph : a visNetwork object
#' @param colors : Character/vector. colors we want to cluster
#' @param label : Character. Label put before value(s). See example
#' @param shape : Character. Shape of cluster(s) if different shapes between nodes or \code{force = T}. "database" per default
#' @param force : If \code{force = FALSE}, Set shape of nodes if all equal, else directly default shape
#'
#' @examples
#'
#' set.seed(124)
#' nodes <- data.frame(id = 1:10, color = c(rep("blue", 6), rep("red", 3), rep("green", 1)))
#' edges <- data.frame(from = round(runif(6)*10), to = round(runif(6)*10))
#'
#' visNetwork(nodes, edges) %>%
#' visClusteringByColor(colors = c("blue"))
#'
#' nodes <- data.frame(id = 1:10, label = paste("Label", 1:10),
#' group = sample(c("A", "B"), 10, replace = TRUE))
#' edges <- data.frame(from = c(2,5,10), to = c(1,2,10))
#'
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", color = "red", shape = "square") %>%
#' visGroups(groupname = "B", color = "yellow", shape = "triangle") %>%
#' visClusteringByColor(colors = c("red"), label = "With color ") %>%
#' visClusteringByGroup(groups = c("B"), label = "Group : ") %>%
#' visLegend()
#'
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", color = "red", shape = "triangle") %>%
#' visGroups(groupname = "B", color = "yellow", shape = "triangle") %>%
#' visClusteringByGroup(groups = c("A","B")) %>%
#' visLegend()
#' @export
visClusteringByColor <- function(graph, colors, label = "Cluster on color : ",
shape = "database", force = FALSE){
if(any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visClusteringByColor with visNetworkProxy object")
}
if(!any(class(graph) %in% "visNetwork")){
stop("graph must be a visNetwork object")
}
shape <- rep(shape, length(colors))[1:length(colors)]
force <- rep(force, length(colors))[1:length(colors)]
if(length(colors) == 1){
colors <- list(colors)
}
clusteringColor<- list(colors = colors, label = label, shape = shape, force = force)
graph$x$clusteringColor <- clusteringColor
graph
}
#' Network visualization clustering options - by hubsize
#'
#' Network visualization clustering options - by hubsize
#'
#' @param graph : a visNetwork object
#' @param size : Integer. This method checks all nodes in the network and those with a equal or higher amount of edges than specified with size argument. If size is null (default), the size will be determined as the average value plus two standard deviations.
#'
#' @examples
#'
#' set.seed(124)
#' nodes <- data.frame(id = 1:10, color = c(rep("blue", 6), rep("red", 3), rep("green", 1)))
#' edges <- data.frame(from = round(runif(6)*10), to = round(runif(6)*10))
#'
#' visNetwork(nodes, edges) %>%
#' visClusteringByHubsize()
#'
#' visNetwork(nodes, edges) %>%
#' visClusteringByHubsize(size = 2)
#'
#' @export
visClusteringByHubsize <- function(graph, size = NULL){
if(any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visClusteringByHubsize with visNetworkProxy object")
}
if(!any(class(graph) %in% "visNetwork")){
stop("graph must be a visNetwork object")
}
if(is.null(size)){
clusteringHubsize <- list(size = 0)
}else{
clusteringHubsize <- list(size = size)
}
graph$x$clusteringHubsize <- clusteringHubsize
graph
}
#' Network visualization clustering options - by group
#'
#' Network visualization clustering options - by group.
#'
#' @param graph : a visNetwork object
#' @param groups : Character/vector. groups we want to cluster
#' @param label : Character. Label put before value(s). See example
#' @param shape : Character. Shape of cluster(s) if different shapes between nodes or \code{force = T}. "database" per default
#' @param color : Character. Color of cluster(s) if different colors between nodes or \code{force = T}. "grey" per default
#' @param force : If \code{force = FALSE}, Set shape and color of nodes if all equal, else directly default shape and color
#' @param scale_size : Set size based on cluster population ? Default to TRUE.
#'
#' @examples
#'
#'
#' nodes <- data.frame(id = 1:10, label = paste("Label", 1:10),
#' group = sample(c("A", "B"), 10, replace = TRUE))
#' edges <- data.frame(from = c(2,5,10), to = c(1,2,10))
#'
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", color = "red", shape = "database") %>%
#' visGroups(groupname = "B", color = "yellow", shape = "triangle") %>%
#' visClusteringByGroup(groups = c("B"), label = "Group : ",
#' shape = "ellipse", color = "blue", force = TRUE) %>%
#' visLegend()
#'
#' @export
visClusteringByGroup <- function(graph, groups, label = "Cluster on group : ",
shape = "database", color = "grey",
force = FALSE, scale_size = TRUE){
if(any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visClusteringByGroup with visNetworkProxy object")
}
if(!any(class(graph) %in% "visNetwork")){
stop("graph must be a visNetwork object")
}
color <- rep(color, length(groups))[1:length(groups)]
shape <- rep(shape, length(groups))[1:length(groups)]
force <- rep(force, length(groups))[1:length(groups)]
scale_size <- rep(scale_size, length(groups))[1:length(groups)]
if(length(groups) == 1){
groups <- list(groups)
}
clusteringGroup<- list(groups = groups, label = label, shape = shape, color = color, force = force, scale_size = scale_size)
graph$x$clusteringGroup <- clusteringGroup
graph
}
#' Network visualization clustering options - by node id
#'
#' Network visualization clustering options - by node id
#'
#' @param graph : a visNetwork object
#' @param nodes : Character/vector. id of nodes we want to cluster
#'
#' @examples
#'
#' set.seed(124)
#' nodes <- data.frame(id = 1:10, color = c(rep("blue", 6), rep("red", 3), rep("green", 1)))
#' edges <- data.frame(from = round(runif(6)*10), to = round(runif(6)*10))
#'
#' visNetwork(nodes, edges) %>%
#' visClusteringByConnection(nodes = 9)
#'
#' @export
visClusteringByConnection <- function(graph, nodes){
if(any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visClusteringByConnection with visNetworkProxy object")
}
if(!any(class(graph) %in% "visNetwork")){
stop("graph must be a visNetwork object")
}
if(length(nodes) == 1){
nodes <- list(nodes)
}
clusteringConnection<- list(nodes = nodes)
graph$x$clusteringConnection <- clusteringConnection
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visClustering.R
|
#' Network visualization collapse / uncollapsed method
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param nodes : a vector of nodes id. NULL for \code{visUncollapse} for open all collapsed nodes
#'@param fit : Optional. Boolean. Default to FALSE. Call fit method after collapse/uncollapse event ?
#'@param resetHighlight : Optional. Boolean. Default to TRUE to reset highlighted nodes after collapse/uncollapse event.
#'@param keepCoord : Optional. Boolean. Default to TRUE to keep nodes coordinates on collapse
#'@param clusterOptions : Optional. List. Default to NULL. A list of all options you want to pass to cluster collapsed node
#'@param labelSuffix : Optional. Character. Use node label + suffix or just suffix. Default to '(cluster)'
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'# You can also disable / enabled the double-click event opening cluster
#'visNetworkProxy("network_id") %>% visEvents(type = "off", doubleClick = "networkOpenCluster")
#'visNetworkProxy("network_id") %>% visEvents(type = "on", doubleClick = "networkOpenCluster")
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
#'@name visNetwork-collapse
#'
visCollapse <- function(graph, nodes, fit = FALSE, resetHighlight = TRUE,
clusterOptions = NULL, labelSuffix = "(cluster)"){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visCollapse with visNetwork object. Only within shiny & using visNetworkProxy")
}
if(length(nodes) == 1){
nodes <- list(nodes)
}
data <- list(id = graph$id, nodes = nodes, fit = fit,
resetHighlight = resetHighlight, labelSuffix = labelSuffix)
data$clusterOptions <- clusterOptions
graph$session$sendCustomMessage("visShinyCollapse", data)
graph
}
#' @name visNetwork-collapse
#'
#' @export
visUncollapse <- function(graph, nodes = NULL, fit = FALSE, resetHighlight = TRUE, keepCoord = TRUE){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visUncollapse with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, fit = fit, resetHighlight = resetHighlight, keepCoord = keepCoord)
if(!is.null(nodes)){
if(length(nodes) == 1){
nodes <- list(nodes)
}
}
data$nodes <- nodes
graph$session$sendCustomMessage("visShinyUncollapse", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visCollapse.R
|
#' Network visualization configure options
#'
#' Network visualization configure options. For full documentation, have a look at \link{visDocumentation}.
#'
#' @param graph : a visNetwork object
#' @param enabled : Boolean. Default to true. Toggle the configuration interface on or off. This is an optional parameter. If left undefined and any of the other properties of this object are defined, this will be set to true.
#' @param filter : String, Array, Boolean, Function. Default to true. When a boolean, true gives you all options, false will not show any. If a string is supplied, any combination of the following is allowed: nodes, edges, layout, interaction, manipulation, physics, selection, renderer. Feel free to come up with a fun seperating character. Finally, when supplied an array of strings, any of the previously mentioned fields are accepted.
#' @param container : DOM element. This allows you to put the configure list in another HTML container than below the network.
#' @param showButton : Boolean. Default to true. Show the generate options button at the bottom of the configurator.
#'
#'@examples
#'
#'\dontrun{
#'
#' nodes <- data.frame(id = 1:3, title = paste0("<p>", 1:3,"<br> tooltip</p>"))
#' edges <- data.frame(from = c(1,2), to = c(1,3))
#'
#' visNetwork(nodes, edges) %>%
#' visConfigure(enabled = TRUE, filter = "interaction")
#'
#' # using visNetworkEditor
#' network <- visNetwork(nodes, edges)
#' custom_network <- visNetworkEditor(object = network)
#' custom_network
#'
#' custom_network <- visNetworkEditor(object = network, filter = "nodes,edges")
#' custom_network
#'}
#'
#'@seealso \link{visConfigure}, \link{visTree}, \link{visNetworkEditor}
#'
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
#'
#' @export
visConfigure <- function(graph,
enabled = NULL,
filter = NULL,
container = NULL,
showButton = NULL){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
configure <- list()
configure$enabled <- enabled
configure$filter <- filter
configure$container <- container
configure$showButton <- showButton
if(any(class(graph) %in% "visNetwork_Proxy")){
options <- list(configure = configure)
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyOptions",data)
}else{
graph$x$options$configure <- configure
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visConfigure.R
|
#' View full documentation of vis.js on network
#'
#' View full documentation of vis.js on network
#'
#'
#' @examples
#'
#' \dontrun{
#' visDocumentation()
#' }
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @import htmlwidgets
#'
#' @export
#' @importFrom utils browseURL
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
#'
visDocumentation <- function(){
browseURL(system.file("docjs/network/index.html", package = "visNetwork"))
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visDocumentation.R
|
#' Network visualization edges options
#'
#' Network visualization edges options. For full documentation, have a look at \link{visDocumentation}.
#'
#' @param graph : a visNetwork object
#' @param title : String. Default to undefined. The title is shown in a pop-up when the mouse moves over the edge.
#' @param value : Number. Default to undefined. When a value is set, the edges' width will be scaled using the options in the scaling object defined above.
#' @param label : String. Default to undefined. The label of the edge. HTML does not work in here because the network uses HTML5 Canvas.
#' @param length : Number. Default to undefined. The physics simulation gives edges a spring length. This value can override the length of the spring in rest.
#' @param width : Number. Default to 1. The width of the edge. If value is set, this is not used.
#' @param dashes : Array or Boolean. Default to false. When true, the edge will be drawn as a dashed line. You can customize the dashes by supplying an Array. Array formart: Array of numbers, gap length, dash length, gap length, dash length, ... etc. The array is repeated until the distance is filled. When using dashed lines in IE versions older than 11, the line will be drawn straight, not smooth.
#' @param hidden : Boolean. Default to false. When true, the edge is not drawn. It is part still part of the physics simulation however!
#' @param hoverWidth : Number or Function. Default to 0.5. Assuming the hover behaviour is enabled in the interaction module, the hoverWidth determines the width of the edge when the user hovers over it with the mouse. If a number is supplied, this number will be added to the width. Because the width can be altered by the value and the scaling functions, a constant multiplier or added value may not give the best results. To solve this, you can supply a function.
#' @param id : String. Default to undefined. The id of the edge. The id is optional for edges. When not supplied, an UUID will be assigned to the edge.
#' @param physics : Boolean. Default to true. When true, the edge is part of the physics simulation. When false, it will not act as a spring.
#' @param selectionWidth : Number or Function. Default to 1. The selectionWidth determines the width of the edge when the edge is selected. If a number is supplied, this number will be added to the width. Because the width can be altered by the value and the scaling functions, a constant multiplier or added value may not give the best results. To solve this, you can supply a function.
#' @param selfReferenceSize : Number. Default to false. When the to and from nodes are the same, a circle is drawn. This is the radius of that circle. This property is deprecated please use selfReference instead.
#' @param selfReference : See \link{visDocumentation}
#' @param labelHighlightBold : Boolean. Default to true. Determines whether or not the label becomes bold when the edge is selected.
#'
#' @param color : Named list or String. Default to named list. Color information of the edge in every situation. Can be 'rgba(120,32,14,1)', '#97C2FC' (hexa notation on 7 char without transparency) or 'red'.
#' \itemize{
#' \item{"color"}{ : String. Default to '#848484. The color of the edge when it is not selected or hovered over (assuming hover is enabled in the interaction module).}
#' \item{"highlight "}{ : String. Default to '#848484'. The color the edge when it is selected.}
#' \item{"hover"}{ : String. Default to '#848484'. The color the edge when the mouse hovers over it (assuming hover is enabled in the interaction module).}
#' \item{"inherit"}{ : String or Boolean. Default to 'from'. When color, highlight or hover are defined, inherit is set to false! Supported options are: true, false, 'from','to','both'.}
#' \item{"opacity"}{ : Number. Default to 1.0. It can be useful to set the opacity of an edge without manually changing all the colors. The allowed range of the opacity option is between 0 and 1.}
#'}
#'
#' @param font : Named list or String. This object defines the details of the label. A shorthand is also supported in the form 'size face color' for example: '14px arial red'
#' \itemize{
#' \item{"color"}{ : String. Default to '#343434'. Color of the label text.}
#' \item{"size"}{ : Number. Default to 14. Size of the label text.}
#' \item{"face"}{ : String. Default to 'arial. Font face (or font family) of the label text.}
#' \item{"background"}{ : String. Default to undefined. When not undefined but a color string, a background rectangle will be drawn behind the label in the supplied color.}
#' \item{"strokeWidth"}{ : Number. Default to 2. As an alternative to the background rectangle, a stroke can be drawn around the text. When a value higher than 0 is supplied, the stroke will be drawn.}
#' \item{"strokeColor"}{ : String. Default to '#ffffff'. This is the color of the stroke assuming the value for stroke is higher than 0.}
#' \item{"align"}{ : String. Default to 'horizontal'. Possible options: 'horizontal','top','middle','bottom'. The alignment determines how the label is aligned over the edge. The default value horizontal aligns the label horizontally, regardless of the orientation of the edge. When an option other than horizontal is chosen, the label will align itself according to the edge.}
#' \item{"vadjust, multi, bold, ital, boldital, mono"}{See \link{visDocumentation}}
#'}
#'
#' @param arrows : Named list or String. To draw an arrow with default settings a string can be supplied. For example: 'to, from,middle' or 'to;from', any combination with any seperating symbol is fine.
#' If you want to control the size of the arrowheads, you can supply an object. See \link{visDocumentation}
#'
#' @param arrowStrikethrough : Boolean. Default to True. When false, the edge stops at the arrow. This can be useful if you have thick lines and you want the arrow to end in a point. Middle arrows are not affected by this.
#'
#' @param smooth : Boolean | named list. Default to named list. When true, the edge is drawn as a dynamic quadratic bezier curve. The drawing of these curves takes longer than that of straight curves but it looks better.
#' \itemize{
#' \item{"enabled"}{ : Boolean. Default to true. Toggle smooth curves on and off. This is an optional option. If any of the other properties in this object are set, this option will be set to true.}
#' \item{"type"}{ : String. Default to 'dynamic'. Possible options: 'dynamic', 'continuous', 'discrete', 'diagonalCross', 'straightCross', 'horizontal', 'vertical', 'curvedCW', 'curvedCCW', 'cubicBezier'.}
#' \item{"roundness"}{ : Number. Default to 0.5. Accepted range: 0 .. 1.0. This parameter tweaks the roundness of the smooth curves for all types EXCEPT dynamic.}
#' \item{"forceDirection"}{ : String or Boolean. Default to false. Accepted options: ['horizontal', 'vertical', 'none']. This options is only used with the cubicBezier curves. When true, horizontal is chosen, when false, the direction that is larger (x distance between nodes vs y distance between nodes) is used. If the x distance is larger, horizontal. This is ment to be used with hierarchical layouts. }
#'}
#'
#' @param shadow : Boolean | named list. Default to false. When true, the edges casts a shadow using the default settings. This can be further refined by supplying a list
#' \itemize{
#' \item{"enabled"}{ : Boolean. Default to false. Toggle the casting of shadows. If this option is not defined, it is set to true if any of the properties in this object are defined.}
#' \item{"color"}{ : String. Default to 'rgba(0,0,0,0.5)'. The color of the shadow as a string. Supported formats are 'rgb(255,255,255)', 'rgba(255,255,255,1)' and '#FFFFFF'.}
#' \item{"size"}{ : Number. Default to 10. The blur size of the shadow.}
#' \item{"x"}{ : Number. Default to 5. The x offset.}
#' \item{"y"}{ : Number. Default to 5. The y offset.}
#'}
#'
#' @param scaling : Named list. If the value option is specified, the size of the edges will be scaled according to the properties in this object.
#' \itemize{
#' \item{"min"}{ : Number. Default to 10. If edges have a value, their sizes are determined by the value, the scaling function and the min max values.}
#' \item{"max"}{ : Number. Default to 30. This is the maximum allowed size when the edges are scaled using the value option.}
#' \item{"label"}{ : Named list or Boolean. Default to Named list. This can be false if the label is not allowed to scale with the node. If true it will scale using default settigns. For further customization, you can supply an object.
#' \itemize{
#' \item{"enabled"}{ : Boolean. Default to false. Toggle the scaling of the label on or off. If this option is not defined, it is set to true if any of the properties in this object are defined.}
#' \item{"min"}{ : Number. Default to 14. The minimum font-size used for labels when scaling.}
#' \item{"max"}{ : Number. Default to 30. The maximum font-size used for labels when scaling.}
#' \item{"maxVisible"}{ : Number. Default to 30. When zooming in, the font is drawn larger as well. You can limit the perceived font size using this option. If set to 30, the font will never look larger than size 30 zoomed at 100\%.}
#' \item{"drawThreshold"}{ : Number. Default to 5. When zooming out, the font will be drawn smaller. This defines a lower limit for when the font is drawn. When using font scaling, you can use this together with the maxVisible to first show labels of important nodes when zoomed out and only show the rest when zooming in.}
#' }
#' }
#' \item{"customScalingFunction"}{ : Function. If nodes have value fields, this function determines how the size of the nodes are scaled based on their values.}
#'}
#'
#' @param widthConstraint : See \link{visDocumentation}
#' @param chosen : See \link{visDocumentation}
#' @param endPointOffset : See \link{visDocumentation}
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'
#' nodes <- data.frame(id = 1:3)
#' edges <- data.frame(from = c(1,2), to = c(1,3))
#'
#' # arrows
#' visNetwork(nodes, edges) %>% visEdges(arrows = 'from')
#' visNetwork(nodes, edges) %>% visEdges(arrows = 'to, from')
#'
#' \dontrun{
#' visNetwork(nodes, edges) %>%
#' visEdges(arrows = list(to = list(enabled = TRUE,
#' scaleFactor = 2, type = 'circle')))
#'
#' # global smooth
#' visNetwork(nodes, edges) %>% visEdges(smooth = FALSE)
#' visNetwork(nodes, edges) %>% visEdges(smooth = list(enabled = TRUE, type = "diagonalCross"))
#'
#' # individual smooth
#' edges <- data.frame(from = c(1,2), to = c(2,3))
#' edges$smooth.enabled <- c(TRUE, TRUE)
#' edges$smooth.type <- c("discrete", "curvedCW")
#' edges$smooth.roundness <- c(0.5, 1)
#' visNetwork(nodes, edges)
#'
#' # width
#' visNetwork(nodes, edges) %>% visEdges(width = 10)
#'
#' # color
#' visNetwork(nodes, edges) %>% visEdges(color = list(hover = "green")) %>%
#' visInteraction(hover = TRUE)
#' visNetwork(nodes, edges) %>% visEdges(color = "red")
#' visNetwork(nodes, edges) %>% visEdges(color = list(color = "red", highlight = "yellow"))
#'
#' # shadow
#' visNetwork(nodes, edges) %>% visEdges(shadow = TRUE)
#' visNetwork(nodes, edges) %>% visEdges(shadow = list(enabled = TRUE, size = 5))
#'
#' # arrows
#' visNetwork(nodes, edges) %>%
#' visEdges(arrows = list(to = list(enabled = TRUE, type = "bar")))
#'
#' # dashes
#' # globally
#' visNetwork(nodes, edges) %>% visEdges(dashes = TRUE)
#'
#' # set configuration individualy
#' # have to use specific notation...
#' nodes <- data.frame(id = 1:3)
#' edges <- data.frame(from = c(1,2), to = c(1,3),
#' dashes = c("[10,10,2,2]", "false"))
#'
#' visNetwork(nodes, edges)
#'
#' edges <- data.frame(from = c(1,2), to = c(1,3),
#' dashes = c("[10,10,2,2]", "[2]"))
#'
#' visNetwork(nodes, edges)
#' }
#' @export
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visEdges <- function(graph,
title = NULL,
value = NULL,
label = NULL,
length = NULL,
width = NULL,
dashes = NULL,
hidden = NULL,
hoverWidth = NULL,
id = NULL,
physics = NULL,
selectionWidth = NULL,
selfReferenceSize = NULL,
selfReference = NULL,
labelHighlightBold = NULL,
color = NULL,
font = NULL,
arrows = NULL,
arrowStrikethrough = NULL,
smooth = NULL,
shadow = NULL,
scaling = NULL,
widthConstraint = NULL,
chosen = NULL,
endPointOffset = NULL){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
edges <- list()
edges$title <- title
edges$value <- value
edges$label <- label
edges$length <- length
edges$width <- width
edges$dashes <- dashes
edges$hidden <- hidden
edges$hoverWidth <- hoverWidth
edges$id <- id
edges$physics <- physics
edges$selectionWidth <- selectionWidth
if(is.null(selfReference)){
edges$selfReferenceSize <- selfReferenceSize
} else {
edges$selfReference <- selfReference
}
edges$labelHighlightBold <- labelHighlightBold
edges$arrows <- arrows
edges$arrowStrikethrough <- arrowStrikethrough
edges$color <- color
edges$font <- font
edges$smooth <- smooth
edges$shadow <- shadow
edges$widthConstraint <- widthConstraint
edges$chosen <- chosen
if(!is.null(scaling)){
if("customScalingFunction"%in%names(scaling)){
scaling$customScalingFunction <- JS(scaling$customScalingFunction)
}
}
edges$scaling <- scaling
edges$endPointOffset <- endPointOffset
if(any(class(graph) %in% "visNetwork_Proxy")){
options <- list(edges = edges)
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyOptions",data)
}else{
graph$x$options$edges <- mergeLists(graph$x$options$edges, edges)
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visEdges.R
|
#' Network export configuration
#'
#' Network export configuration. This function only work within shiny or a web browser.
#'
#'@param graph : a visNetwork object
#'@param type : Type of export. One of "png" (default), "jpeg" or "pdf"
#'@param name : name of imgage, default to "network"
#'@param label : Label on button, default to "Export as png/jpeg/pdf"
#'@param background : background color, default to white (#fff). Work only if network background is transparent.
#'@param float : button postion, default to "right"
#'@param style : button css style.
#'@param loadDependencies / Boolean. TRUE by default. Load libraries for export (fileSaver, Blob, canvastoBlob, html2canvas, jsPDF)
#'@param ... : arguments for \link{addExport}
#'
#'@examples
#'
#'\dontrun{
#'
#'nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
#'edges <- data.frame(from = c(1,2), to = c(2,3))
#'
#'visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", color = "red") %>%
#' visGroups(groupname = "B", color = "lightblue") %>%
#' visLegend() %>% visExport()
#'
#'visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", color = "red") %>%
#' visGroups(groupname = "B", color = "lightblue") %>%
#' visLegend() %>% visExport(type = "jpeg", name = "export-network",
#' float = "left", label = "Save network", background = "purple", style= "")
#'
#'}
#'@seealso \link{visSave}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visExport <- function(graph, type = "png", name = "network",
label = paste0("Export as ", type),
background = "#fff", float = "right",
style = NULL, loadDependencies = TRUE, ...){
if(any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visExport with visNetworkProxy object")
}
if(!any(class(graph) %in% "visNetwork")){
stop("graph must be a visNetwork object")
}
stopifnot(type%in%c("png", "jpeg", "pdf"))
if(is.null(style)){
css <- paste0("float:", float,
";-webkit-border-radius: 10;
-moz-border-radius: 10;
border-radius: 10px;
font-family: Arial;
color: #ffffff;
font-size: 12px;
background: #090a0a;
padding: 4px 8px 4px 4px;
text-decoration: none;")
}else{
css <- paste0("float:", float, ";", style)
}
export <- list()
export$type <- type
export$css <- css
export$background <- background
export$name <- paste0(name, ".", type)
export$label <- label
graph$x$export <- export
if(loadDependencies){
graph <- addExport(graph, ...)
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visExport.R
|
#' Network visualization fit method
#'
#' For use fit() method in a shiny app. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param nodes : NULL for all nodes (Default), or a vector of nodes id
#'@param animation : Optional. List. For animation you can define the duration (in milliseconds) and easing function manually.
#'Available are: linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint.
#'Default to list(duration = 1500, easingFunction = "easeInOutQuad")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visFit <- function(graph, nodes = NULL,
animation = list(duration = 1500, easingFunction = "easeInOutQuad")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visFit with visNetwork object. Only within shiny & using visNetworkProxy")
}
options <- list(animation = animation)
if(!is.null(nodes)){
if(length(nodes) == 1){
nodes <- list(nodes)
}
}
options$nodes <- nodes
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyFit", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visFit.R
|
#' Network visualization focus method
#'
#' For use focus() method in a shiny app. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param id : a node id
#'@param scale : Optional. Number. The scale is the target zoomlevel. Default value is 2.0.
#'@param offset : Optional. List. The offset (in DOM units) is how many pixels from the center the view is focussed. Default value is list(x = 0, y = 0).
#'@param locked : Optional. Boolean. Locked denotes whether or not the view remains locked to the node once the zoom-in animation is finished. Default value is true.
#'@param animation : Optional. List. For animation you can define the duration (in milliseconds) and easing function manually.
#'Available are: linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint.
#'Default to list(duration = 1500, easingFunction = "easeInOutQuad")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visFocus <- function(graph, id, scale = 2,
offset = list(x = 0, y = 0),
locked = TRUE,
animation = list(duration = 1500, easingFunction = "easeInOutQuad")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visFocus with visNetwork object. Only within shiny & using visNetworkProxy")
}
stopifnot(length(id) == 1)
options <- list(scale = scale, offset = offset, locked = locked, animation = animation)
data <- list(id = graph$id, focusId = id, options = options)
graph$session$sendCustomMessage("visShinyFocus", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visFocus.R
|
#' Function to get nodes data, with shiny only.
#'
#' Function to get nodes data, with shiny only.
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param input : name of shiny input created. Default to paste0(graph$id, "_nodes")
#' @param addCoordinates : Boolean. Add coordinates to nodes data ? Default to TRUE.
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetNodes <- function(graph, input = paste0(graph$id, "_nodes"), addCoordinates = T){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetNodes with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, input = input, addCoordinates = addCoordinates)
graph$session$sendCustomMessage("visShinyGetNodes", data)
graph
}
#' Function to get edges data, with shiny only.
#'
#' Function to get edges data, with shiny only
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param input : name of shiny input created. Default to paste0(graph$id, "_edges")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetEdges <- function(graph, input = paste0(graph$id, "_edges")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetEdges with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, input = input)
graph$session$sendCustomMessage("visShinyGetEdges", data)
graph
}
#' Network visualization getPositions method
#'
#' For use getPositions() method in a shiny app. For full documentation, have a look at \link{visDocumentation}.
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param nodes : NULL for all nodes (Default), or a vector of nodes id
#' @param input : name of shiny input created. Default to paste0(graph$id, "_positions")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetPositions <- function(graph, nodes = NULL, input = paste0(graph$id, "_positions")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetPositions with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, input = input)
data$nodes <- nodes
graph$session$sendCustomMessage("visShinyGetPositions", data)
graph
}
#' Function to get selected nodes, with shiny only.
#'
#' Function to get selected nodes, with shiny only. Returns a vector of selected node ids.
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param input : name of shiny input created. Default to paste0(graph$id, "_selectedNodes")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetSelectedNodes <- function(graph, input = paste0(graph$id, "_selectedNodes")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetSelectedNodes with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, input = input)
graph$session$sendCustomMessage("visShinyGetSelectedNodes", data)
graph
}
#' Function to get selected edges, with shiny only.
#'
#' Function to get selected edges, with shiny only. Returns a vector of selected edge ids.
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param input : name of shiny input created. Default to paste0(graph$id, "_selectedEdges")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetSelectedEdges <- function(graph, input = paste0(graph$id, "_selectedEdges")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetSelectedEdges with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, input = input)
graph$session$sendCustomMessage("visShinyGetSelectedEdges", data)
graph
}
#' Function to get selected edges & nodes, with shiny only.
#'
#' Function to get selected edges & nodes, with shiny only
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param input : name of shiny input created. Default to paste0(graph$id, "_selection")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetSelection <- function(graph, input = paste0(graph$id, "_selection")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetSelection with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, input = input)
graph$session$sendCustomMessage("visShinyGetSelection", data)
graph
}
#' Function to get current scale of network, with shiny only.
#'
#' Function to get current scale of network, with shiny only. Returns the current scale of the network. 1.0 is comparible to full, 0 is zoomed out infinitely.
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param input : name of shiny input created. Default to paste0(graph$id, "_scale")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetScale <- function(graph, input = paste0(graph$id, "_scale")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetScale with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, input = input)
graph$session$sendCustomMessage("visShinyGetScale", data)
graph
}
#' Function to get current view position, with shiny only.
#'
#' Function to get current view position, with shiny only. Returns the current central focus point of the view.
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param input : name of shiny input created. Default to paste0(graph$id, "_viewPosition")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetViewPosition <- function(graph, input = paste0(graph$id, "_viewPosition")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetViewPosition with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, input = input)
graph$session$sendCustomMessage("visShinyGetViewPosition", data)
graph
}
#' Method getConnectedEdges, with shiny only.
#'
#' Method getConnectedEdges, with shiny only. Returns a vector of edgeIds of the edges connected to this node.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param id : a node id
#'@param input : name of shiny input created. Default to paste0(graph$id, "_connectedEdges")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetConnectedEdges <- function(graph, id, input = paste0(graph$id, "_connectedEdges")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetConnectedEdges with visNetwork object. Only within shiny & using visNetworkProxy")
}
stopifnot(length(id) == 1)
data <- list(id = graph$id, nodeId = id, input = input)
graph$session$sendCustomMessage("visShinyGetConnectedEdges", data)
graph
}
#' Method getConnectedNodes, with shiny only.
#'
#' Method getConnectedNodes, with shiny only. Returns a vector of nodeIds of the all the nodes that are directly connected to this node. If you supply an edgeId, vis will first match the id to nodes.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param id : a node or edge id
#'@param input : name of shiny input created. Default to paste0(graph$id, "_connectedNodes")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetConnectedNodes <- function(graph, id, input = paste0(graph$id, "_connectedNodes")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetConnectedNodes with visNetwork object. Only within shiny & using visNetworkProxy")
}
stopifnot(length(id) == 1)
data <- list(id = graph$id, nodeId = id, input = input)
graph$session$sendCustomMessage("visShinyGetConnectedNodes", data)
graph
}
#' Method getBoundingBox, with shiny only.
#'
#' Method getBoundingBox, with shiny only. Returns a bounding box for the node including label in the format. These values are in canvas space.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param id : a node or edge id
#'@param input : name of shiny input created. Default to paste0(graph$id, "_boundingBox")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGetBoundingBox <- function(graph, id, input = paste0(graph$id, "_boundingBox")){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetBoundingBox with visNetwork object. Only within shiny & using visNetworkProxy")
}
stopifnot(length(id) == 1)
data <- list(id = graph$id, nodeId = id, input = input)
graph$session$sendCustomMessage("visShinyGetBoundingBox", data)
graph
}
#' Method storePositions, with shiny only.
#'
#' Method storePositions, with shiny only. Put the X and Y positions of all nodes into that dataset.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visStorePositions <- function(graph){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visStorePositions with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id)
graph$session$sendCustomMessage("visShinyStorePositions", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visGetUtils.R
|
#' Network visualization groups options
#'
#' Network visualization groups options. For full documentation, have a look at \link{visDocumentation}.
#'
#' @param graph : a visNetwork object
#' @param useDefaultGroups : Boolean. Default to true. If your nodes have groups defined that are not in the Groups module, the module loops over the groups it does have, allocating one for each unknown group. When all are used, it goes back to the first group. By setting this to false, the default groups will not be used in this cycle.
#' @param groupname : String. Name of target group.
#' @param ... : \link{visNodes}. You can add multiple groups containing styling information that applies to a certain subset of groups. All options described in the nodes module that make sense can be used here (you're not going to set the same id or x,y position for a group of nodes)
#'
#' @examples
#'
#' nodes <- data.frame(id = 1:10, label = paste("Label", 1:10),
#' group = sample(c("A", "B"), 10, replace = TRUE))
#' edges <- data.frame(from = c(2,5,10), to = c(1,2,10))
#'
#' visNetwork(nodes, edges) %>%
#' visLegend() %>%
#' visGroups(groupname = "A", color = "red", shape = "database") %>%
#' visGroups(groupname = "B", color = "yellow", shape = "triangle")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @export
#'
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visGroups <- function(graph,
useDefaultGroups = TRUE,
groupname = NULL,
...){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
groups <- list()
groups$useDefaultGroups <- useDefaultGroups
params <- list(...)
if(length(params) > 0){
if(is.null(groupname)){
stop("Must have a groupname to identify group")
}
tmp <- list(...)
if("icon" %in% names(tmp)){
if(!"color" %in% names(tmp$icon)){
tmp$icon$color <- '#2B7CE9'
}
}
if("scaling" %in% names(tmp)){
if("customScalingFunction"%in%names(tmp$scaling)){
tmp$scaling$customScalingFunction <- JS(tmp$scaling$customScalingFunction)
}
}
groups[[groupname]] <- tmp
}
if(any(class(graph) %in% "visNetwork_Proxy")){
options <- list(groups = groups)
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyOptions",data)
}else{
graph$x$options$groups <- mergeLists(graph$x$options$groups, groups)
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visGroups.R
|
#' Visualize Hierarchical cluster analysis.
#'
#' Visualize Hierarchical cluster analysis \code{hclust}. This function compute distance using \code{dist}, and
#' Hierarchical cluster analysis using \code{hclust} (from stats package or flashClust if installed), and
#' render the tree with visNetwork, adding informations. Can also be called on a \code{hclust} or \code{dist} object.
#' Needed packages : sparkline (graphics on tooltip), ggraph, igraph, flashClust
#'
#' @param object \code{hclust | dist | data.frame}.
#' @param data \code{data.frame}, data.frame with data. Only for \code{hclust} or \code{dist} object.
#' @param main Title. See \link{visNetwork}
#' @param submain Subtitle. See \link{visNetwork}
#' @param footer Footer. See \link{visNetwork}
#' @param distColumns \code{numeric}, indice of columns used for compute distance.
#' If \code{NULL} (default), keep all \code{numeric} and \code{integer} columns.
#' If Not \code{NULL}, keep only \code{numeric} and \code{integer} columns
#' @param distMethod \code{character}, the distance measure to be used for \code{\link[stats]{dist}} function. Default to 'euclidean'.
#' @param hclustMethod \code{character}, the agglomeration method to be used for \code{\link[stats]{hclust}} function. Default to 'complete'.
#' @param cutree \code{numeric} or \code{integer}, desired number of groups. Default to 0.
#' @param tooltipColumns \code{numeric}, adding mini-graphics in tooltips using \code{sparkline} ? Indice of columns used in tooltip. All by default.
#' So, we add boxplot / pie focus on sub-population vs all population using \code{sparkline} package. \code{NULL} to disable.
#' @param colorEdges \code{character}, color of edges. Default to 'black'.
#' @param colorGroups \code{character}, color for group in hexa ("#00FF00"). Default rainbow.
#' @param minNodeSize \code{numeric}, in case of \code{nodesPopSize}, minimum size of a node. Default to 50. Else \code{minNodeSize + maxNodeSize / 2}.
#' @param maxNodeSize \code{numeric}, in case of \code{nodesPopSize}, maximum size of a node. Default to 200. Else \code{ minNodeSize + maxNodeSize / 2}.
#' @param nodesPopSize \code{boolean}, nodes sizes depends on population ? Default to \code{TRUE}.
#' @param highlightNearest \code{boolean}, highlight sub-tree on click ? Default to \code{TRUE}.
#' @param horizontal \code{boolean}, default to FALSE
#' @param height \code{character}, default to "600px"
#' @param width \code{character}, default to "100\%"
#' @param export \code{boolean}, add button for export. Default to TRUE
#' @param ... Don't use
#'
#' @examples
#'
#' \dontrun{
#'
#' #--------------
#' # data.frame
#' #--------------
#'
#' # default call on data.frame
#' visHclust(iris, cutree = 3, colorEdges = "red")
#'
#' # update some parameters
#' visHclust(iris, cutree = 3, tooltipColumns = c(1, 5),
#' colorGroups = c("red", "blue", "green"), horizontal = TRUE)
#'
#' # no graphics on tooltip
#' visHclust(iris, cutree = 3, tooltipColumns = NULL,
#' main = "Hclust on iris")
#'
#' # Title(s)
#' visHclust(iris, cutree = 3, main ="My_title",
#' submain = "My_sub_title", footer = "My_footer")
#'
#' # Export
#' visHclust(iris, cutree = 3, export = TRUE)
#'
#'
#' # update group / individual nodes
#' visHclust(iris, cutree = 8) %>%
#' visGroups(groupname = "group", color ="black",
#' shape = "triangleDown", size = 75) %>%
#' visGroups(groupname = "individual",
#' font = list(size = 150),
#' color = list(background = "white", border = "purple",
#' highlight = "#e2e9e9", hover = "orange"), shape = "box")
#'
#' #--------------
#' # dist
#' #--------------
#'
#' # without adding data & info in tooltip
#' visHclust(dist(iris[,1:4]), cutree = 3)
#'
#' # adding data & info in tooltip
#' visHclust(dist(iris[,1:4]), cutree = 3, data = iris)
#'
#' #--------------
#' # hclust
#' #--------------
#'
#' # without adding data & info in tooltip
#' visHclust(hclust(dist(iris[,1:4])), cutree = 3)
#'
#' # adding data & info in tooltip
#' visHclust(hclust(dist(iris[,1:4])), cutree = 3, data = iris)
#'
#' }
#'
#' @importFrom grDevices rainbow
#' @importFrom stats dist hclust na.omit
#'
#' @export
visHclust <- function(object, ...) UseMethod("visHclust")
#' @rdname visHclust
#' @export
#'
visHclust.default <- function(object, ...) visHclust.data.frame(object, ...)
#' @rdname visHclust
#' @export
visHclust.data.frame <- function(object, main = "", submain = "", footer = "",
distColumns = NULL,
distMethod = "euclidean",
hclustMethod = "complete",
cutree = 0,
tooltipColumns = 1:ncol(object),
colorEdges = "black",
colorGroups = substr(rainbow(cutree),1, 7),
highlightNearest = TRUE,
horizontal = FALSE,
minNodeSize = 50,
maxNodeSize = 200,
nodesPopSize = TRUE,
height = "600px", width = "100%", export = TRUE, ...){
# Control on inputs
.ctrlArgsvisHcl(distColumns, cutree, object)
# Control packages
.ctrlPckvisHcl(tooltipColumns)
# Control data
object <- .ctrlDatavisHcl(object)
# Give name to draw
drawNames <- .giveDrawNamevisHcl(object, tooltipColumns)
# Manage color grp
colorGroups <- .manageColorGroupHlc(colorGroups, cutree)
# Give data for dist
dataForHcl <- .giveDataForHcl(object, distColumns)
# Hclust calc
dist <- dist(dataForHcl, method = distMethod)
# Node size control
if(nodesPopSize){
minNodeSize = minNodeSize
maxNodeSize = maxNodeSize
}else{
minNodeSize = (minNodeSize + maxNodeSize) / 2
maxNodeSize = minNodeSize
}
visHclust.dist(object = dist, data = object, main = main,
submain = submain, footer = footer,
cutree = cutree,
hclustMethod = hclustMethod,
tooltipColumns = tooltipColumns,
colorEdges = colorEdges,
colorGroups = colorGroups,
highlightNearest = highlightNearest,
horizontal = horizontal,
minNodeSize = minNodeSize,
maxNodeSize = maxNodeSize,
nodesPopSize = nodesPopSize,
height = height, width = width, export = export)
}
#' @rdname visHclust
#' @export
visHclust.dist <- function(object, data = NULL, main = "", submain = "", footer = "",
cutree = 0,
hclustMethod = "complete",
tooltipColumns = if(!is.null(data)){1:ncol(data)} else {NULL},
colorEdges = "black",
colorGroups = substr(rainbow(cutree),1, 7),
highlightNearest = TRUE,
horizontal = FALSE,
minNodeSize = 50,
maxNodeSize = 200,
nodesPopSize = TRUE,
height = "600px", width = "100%", export = TRUE, ...){
# flashClust
f_hclust <- .giveFhcl()
if(!is.null(data)){
if(attr(object, "Size")!= nrow(data)){
stop("'dist' matrix and 'data' must have same number of rows")
}
}
hcl <- f_hclust(d = object, method = hclustMethod)
visHclust.hclust(object = hcl, data = data, main = main,
submain = submain, footer = footer,
cutree = cutree,
tooltipColumns = tooltipColumns,
colorEdges = colorEdges,
colorGroups = colorGroups,
highlightNearest = highlightNearest,
horizontal = horizontal,
minNodeSize = minNodeSize,
maxNodeSize = maxNodeSize,
nodesPopSize = nodesPopSize,
height = height, width = width, export = export)
}
#' @rdname visHclust
#' @export
visHclust.hclust <- function(object, data = NULL, main = "", submain = "", footer = "",
cutree = 0,
tooltipColumns = if(!is.null(data)){
1:ncol(data)
} else {NULL},
colorEdges = "black",
colorGroups = substr(rainbow(cutree),1, 7),
highlightNearest = TRUE,
horizontal = FALSE,
minNodeSize = 50,
maxNodeSize = 200,
nodesPopSize = TRUE,
height = "600px", width = "100%", export = TRUE, ...){
if(!is.null(data)){
if(length(object$order)!=nrow(data)){
stop("object and data mush contain same number of individuals")
}
}
if(!is.null(data)){
drawNames <- .giveDrawNamevisHcl(data, tooltipColumns)
}else{
drawNames <- NULL
}
# Convert data for viz
res <- .convertHclust(object, data, drawNames,
minNodeSize = minNodeSize, maxNodeSize = maxNodeSize)
# Make graph
.makeHlcGraph(res, nodesPopSize, minNodeSize, maxNodeSize,
colorEdges, cutree, colorGroups,
height, width, main, horizontal,
submain, footer, highlightNearest, export)
}
#' Transform data from hclust to nodes and edges
#'
#' @noRd
#'
.convertHclust <- function(hcl, data, drawNames,
minNodeSize, maxNodeSize)
{
ig <- suppressMessages({
tidygraph::as.igraph(tidygraph::as_tbl_graph(hcl, directed = TRUE, mode = "out"))
})
neig <- igraph::neighborhood(ig, 150000, mode = "out")
neig <- sapply(1:length(neig), function(i){
neig[[i]][!neig[[i]] == i]
}, simplify = FALSE)
dta <- toVisNetworkData(ig, idToLabel = FALSE)
dta <- lapply(dta, data.frame, stringsAsFactors = FALSE)
dta$nodes$label <- as.character(dta$nodes$label)
dta$nodes$labelComplete <- ""
dta$nodes$neib <- I(neig)
if(!is.null(drawNames)){
classDtaIn <- unlist(lapply(data, function(X){class(X)[1]}))
classDtaIn <- classDtaIn%in%c("numeric", "integer")
dataNum <- data[,classDtaIn, drop = FALSE]
dataNum <- dataNum[,names(dataNum)%in%drawNames, drop = FALSE]
if(ncol(dataNum) > 0){
minPop <- apply(dataNum, 2, min, na.rm = T)
maxPop <- apply(dataNum, 2, max, na.rm = T)
meanPop <- colMeans(dataNum, na.rm = TRUE)
popSpkl <- apply(dataNum,2, function(X){
.addSparkLineOnlyJs(X, type = "box")
})
rNum <- 1:nrow(dataNum)
dta$nodes$labelComplete <- sapply(1:nrow(dta$nodes), function(Z){
if(!dta$nodes[Z,]$leaf){
nodeDep <- dta$nodes[Z,]$neib[[1]]
nodeDep <- as.numeric(dta$nodes$label[dta$nodes$id%in%nodeDep])
nodeDep <- nodeDep[nodeDep%in%rNum]
.giveLabelsFromDfWhichInvisible(dataNum[nodeDep,, drop = FALSE], popSpkl, minPop, maxPop, meanPop)
}else{""}
})
}
dataOthr <- data[,!classDtaIn, drop = FALSE]
dataOthr <- dataOthr[,names(dataOthr)%in%drawNames, drop = FALSE]
if(ncol(dataOthr) > 0){
popSpkl <- apply(dataOthr,2, function(X){
Y <- sort(table(X))
spl <- .addSparkLineOnlyJs(Y , type = "pie", labels = names(Y))
Y <- data.frame(Y)
Y$X <- ifelse(nchar(as.character(Y$X) ) > 9, paste0(substr(Y$X, 1, 8), "..."), as.character(Y$X))
modP <- Y$X[length(Y$X)]
paste0(spl, " On pop. (mode: <b>", modP, "</b>)")
})
namOrder <- lapply(dataOthr, function(X){
names(sort(table(X)))
})
rNum <- 1:nrow(dataOthr)
dta$nodes$labelComplete <- sapply(1:nrow(dta$nodes), function(Z){
if(!dta$nodes[Z,]$leaf){
nodeDep <- dta$nodes[Z,]$neib[[1]]
nodeDep <- as.numeric(dta$nodes$label[dta$nodes$id%in%nodeDep])
nodeDep <- nodeDep[nodeDep%in%rNum]
paste(dta$nodes[Z,]$labelComplete,.giveLabelsFromDfChrInvisible(dataOthr[nodeDep,, drop = FALSE], popSpkl, namOrder) )
}else{""}
})
}
}
dta$nodes$circular <- NULL
dta$edges$circular <- NULL
dta$nodes$height <- NULL
tmp_layout <- suppressMessages(ggraph::create_layout(hcl, "dendrogram"))
if(".ggraph.orig_index" %in% colnames(tmp_layout)){
tmp_layout <- tmp_layout[order(tmp_layout$.ggraph.orig_index),]
tmp_layout$ggraph.index <- tmp_layout$`.ggraph.orig_index`
}
if("height" %in% colnames(tmp_layout)){
tmp_layout$y <- tmp_layout$height
}
dta$nodes$label <- as.character(tmp_layout$label)
dta$nodes$x <- tmp_layout$x
dta$nodes$y <- tmp_layout$y
dta$nodes$ggraph.index <- tmp_layout$ggraph.index
names(dta$nodes) <- sub("layout.", "", names(dta$nodes))
names(dta$nodes)[which(names(dta$nodes) == "leaf")] <- "hidden"
dta$nodes$hidden2 <- FALSE
dta$nodes$leaf <- dta$nodes$hidden
tpNum <- max(as.numeric(dta$nodes$id)) + 1
dta$edges$horizontal <- FALSE
dta$nodes <- dta$nodes[, c("id", "x", "y", "hidden", "label", "members", "ggraph.index",
"hidden2", "leaf", "neib", "labelComplete")]
outList <- sapply(1:nrow(dta$nodes), function(X){
row <- dta$nodes[X,]
if(row$hidden){
list(row, dta$edges[as.numeric(dta$edges$from) == row$id])
}else{
edRow <- dta$edges[dta$edges$from == row$id,]
idTo <- as.numeric(edRow$to)
XcO <- dta$nodes[dta$nodes$id %in% idTo,]
ret <- do.call("rbind", sapply(1:nrow(edRow), function(Y){
roW <- edRow[Y,]
roW$from
tpNum <- tpNum + X * 100000 + Y
roWEnd <- data.frame(from = c(roW$from, tpNum), to = c(tpNum, roW$to),
label = "", direction = "", horizontal = c(TRUE, FALSE))
roWEnd
}, simplify = FALSE))
XcO <- do.call("rbind",list(XcO,
{
X <- ret$from[!ret$from%in%dta$nodes$id]
data.frame(
id = X,
x = XcO[XcO$id %in% ret[ret$from %in% X,]$to,]$x,
y = dta$nodes[dta$nodes$id %in% ret[ret$to %in% X,]$from,]$y,
hidden = FALSE,
label = 1,
members = dta$nodes[dta$nodes$id %in% ret[ret$from %in% X,]$to,]$members,
ggraph.index = X,
hidden2 = TRUE,
leaf = TRUE,
neib = I(rep(list(numeric()), length(X))),
labelComplete = ""
)
})
)
list(XcO, ret)
}
}, simplify = FALSE)
dta$nodes <- do.call("rbind",(lapply(outList, function(X){X[[1]]})))
dta$edges <- do.call("rbind",(lapply(outList, function(X){X[[2]]})))
dta$edges <- do.call("rbind", (list(data.frame(from = tpNum-1 , to = tpNum, label = "",
direction = "", horizontal = TRUE), dta$edges)))
dta$nodes <- dta$nodes[!duplicated(dta$nodes$id),]
dta$nodes$hidden <- !dta$nodes$hidden
dta$nodes$x <- dta$nodes$x * 200
dta$nodes$y <- -dta$nodes$y * 2000
dta$nodes$title <- paste("Inertia : <b>", round(-dta$nodes$y/2000, 2), "</b><br>Number of individuals : <b>", dta$nodes$members, "</b>")
dta$nodes$inertia <- round(-dta$nodes$y/2000, 2)
dta$nodes$hidden <- NULL
names(dta$nodes)[which(names(dta$nodes) == "hidden2")] <- "hidden"
dta$edges$width <- 20
# Add tooltips on edges
dta$edges$title <- dta$nodes$title[match(dta$edges$to, dta$nodes$id)]
dta$edges$title[dta$edges$horizontal] <- NA
dta$edges$label <- dta$nodes$inertia[match(dta$edges$to, dta$nodes$id)]
dta$edges$label[dta$edges$horizontal] <- NA
dta$edges$from[1] <- dta$nodes[dta$nodes$y == min(dta$nodes$y),]$id[1]
dta$edges$to[1] <- dta$nodes[dta$nodes$y == min(dta$nodes$y),]$id[2]
dta$nodes$group <- ifelse(dta$nodes$leaf, "individual", "group")
# titleDetails <- ifelse(!is.null(drawNames), "<br><b>Details : </b>", "")
titleDetails <- ""
if(!is.null(drawNames)){
titleDetails <- paste0(
'<hr class = "rPartvisNetwork">
<div class ="showOnMe2"><div style="text-align:center;"><U style="color:blue;" onmouseover="this.style.cursor=\'pointer\';" onmouseout="this.style.cursor=\'default\';">Details : </U></div>
<div class="showMeRpartTTp2" style="display:none;margin-top: -15px">
', dta$nodes$labelComplete,
'</script>',
'<script type="text/javascript">',
'$(document).ready(function(){
$(".showOnMe2").click(function(){
$(".showMeRpartTTp2").toggle();
$.sparkline_display_visible();
});
});</script>','</div></div>
')
}
dta$nodes$title <- paste(dta$nodes$title, titleDetails)
dta$nodes$labelComplete <- NULL
dta$nodes[dta$nodes$leaf & !dta$nodes$hidden,]$title <- as.character(dta$nodes[dta$nodes$leaf& !dta$nodes$hidden,]$label)
dta$nodes$scaling.min <- minNodeSize
dta$nodes$scaling.max <- maxNodeSize
dta
}
.giveLabelsFromDf <- function(df, popSpkl = NULL, minPop = NULL, maxPop = NULL, meanPop = NULL){
df <- df[!is.na(df[,1]),, drop = FALSE]
clM <- colMeans(df, na.rm = TRUE)
if(!is.null(popSpkl)){
nm <- names(df)
re <- list()
for(i in nm){
re[[i]] <- paste0("<br>", popSpkl[[i]],' : On pop. (mean:<b>', round(meanPop[i],2),"</b>)","<br>",
.addSparkLine(df[,i], type = "box",
min = minPop[[i]], max = maxPop[[i]]),
" : On grp. (mean:<b>", round(clM[i], 2),"</b>)")
}
}
re <- unlist(re)
paste(paste("<br> <b>",names(clM), ": </b>", re, collapse = ""))
}
.giveLabelsFromDfChr <- function(df, popSpkl, namOrder){
nm <- names(df)
re <- list()
for(i in nm){
tbl <- table(df[,i])
tbl <- tbl[na.omit(match(namOrder[[i]], names(tbl)))]
tbl <- data.frame(tbl)
newMod <- namOrder[[i]][!namOrder[[i]]%in%tbl$Var1]
if(length(newMod) > 0){
tbl <- rbind(tbl, data.frame(Var1 = newMod, Freq = 0))
}
namOrder
tbl$Var1 <- ifelse(nchar(as.character(tbl$Var1) ) > 9, paste0(substr(tbl$Var1, 1, 8), "..."), as.character(tbl$Var1))
re[[i]] <- paste0(.addSparkLine(tbl$Freq, type = "pie", labels = tbl$Var1))
}
re <- unlist(re)
paste(paste("<br> <b>",names(re), ": </b><br>",
popSpkl, "<br>",
re, "On grp. (mode:<b>", tbl[which.max(tbl$Freq),]$Var1,"</b>)", collapse = ""))
}
.addSparkLine <- function(vect, min = NULL, max = NULL, type = "line", labels = NULL){
if(is.null(min)) min <- min(vect, na.rm = T)
if(is.null(max)) max <- max(vect, na.rm = T)
drun <- c(sample(LETTERS, 10, replace = TRUE), sample(1:1000, 5))
drun <- paste0(drun, collapse = "")
if(!is.null(labels)){
tltp <- paste0((1:length(labels))-1, ": '", labels, "'", collapse = ",")
tltp <- paste0("
tooltipFormat: \'{{offset:offset}} ({{percent.1}}%)\', tooltipValueLookups: {
\'offset\': { ", tltp, "}}")
}else{
tltp <- NULL
}
paste0('<script type="text/javascript">
$(function() {
$(".inlinesparkline', drun,'").sparkline([',paste0(vect, collapse = ",") ,'], {
type: "',type , '", chartRangeMin: ', min,', chartRangeMax: ', max,'
, ', tltp, '
});
});
</script>
<span class="inlinesparkline', drun,'"></span>')
}
.ctrlPckvisHcl <- function(tooltipColumns){
miss_packages <- c()
if(!is.null(tooltipColumns)){
if(!requireNamespace("sparkline", quietly = TRUE)){
miss_packages <- c(miss_packages, "'sparkline'")
}
}
if(!requireNamespace("ggraph", quietly = TRUE)){
miss_packages <- c(miss_packages, "'ggraph'")
}
if(!requireNamespace("igraph", quietly = TRUE)){
miss_packages <- c(miss_packages, "'igraph'")
}
if(!requireNamespace("tidygraph", quietly = TRUE)){
miss_packages <- c(miss_packages, "'tidygraph'")
}
if(length(miss_packages) == 1){
stop(miss_packages," package is needed for this function", call. = FALSE)
} else if(length(miss_packages) > 1){
stop(paste(miss_packages, collapse = ", ")," packages are needed for this function", call. = FALSE)
}
invisible(NULL)
}
.ctrlArgsvisHcl <- function(distColumns, cutree, data){
# distColumns
if(!is.null(distColumns)){
if(!all(distColumns) %in% 1:ncol(data)){
stop("all elements of distColumns should be in 1:ncol(data)")
}
}
# cutree control
if(!(is.numeric(cutree) | is.integer(cutree))){
stop("cutree should be 'numeric' or 'integer'")
}else{
if(!cutree %in% 0:nrow(data)){
stop("cutree should be in 0:ncol(data)")
}
}
}
.giveFhcl <- function(){
if(!requireNamespace("flashClust", quietly = TRUE)){
stats::hclust
} else {
flashClust::hclust
}
}
.makeHlcGraph <- function(res, nodesPopSize, minNodeSize, maxNodeSize,
colorEdges, cutree, colorGroups, height, width, main,
horizontal, submain, footer, highlightNearest, export){
res$edges$color <- colorEdges
if(!is.null(cutree)){
if(cutree > 1){
color <- colorGroups
levelCut <- unique(sort(res$nodes$y))[(cutree) - 1] + diff(unique(sort(res$nodes$y))[(cutree)+(-1:0)])/2
Mid <- as.numeric(max(res$nodes$id))
res$nodes <- rbind(res$nodes, data.frame(id = c(Mid+150000, Mid+150001),
x = c(min(res$nodes$x) - 500, max(res$nodes$x) + 500),
y = rep(levelCut, 2),
label = NA,
members = NA,
ggraph.index = NA,
hidden = TRUE,
leaf = FALSE,
title = NA,
neib = I(rep(list(numeric()), 2)),
inertia = NA,
group = "cut",
scaling.min = minNodeSize,
scaling.max = maxNodeSize))
res$edges <- rbind(res$edges, data.frame(
from = Mid+150000,
to = Mid+150001,
label = NA,
direction = "",
horizontal = TRUE,
width = 1,
title= NA,
color = "red"
))
fromY <- merge(res$edges, res$nodes, by.x = "from", by.y = "id")[,c("from", "y")]
toY <- merge(res$edges, res$nodes, by.x = "from", by.y = "id")[,c("to", "y")]
names(toY)[which(names(toY) == "y")] <- "yt"
endY <- merge(fromY, toY, by.x = "from", by.y = "to")
nodesMainClass <- unique(endY[endY$y > levelCut & endY$yt < levelCut,]$from)
nod <- nodesMainClass[1]
nod
ndL <- sapply(nodesMainClass, function(nod){
c(nod, unlist(res$nodes[res$nodes$id == nod,]$neib))
}, simplify = FALSE)
for(i in 1:length(ndL)){
res$edges[res$edges$from %in% ndL[[i]] | res$edges$to %in% ndL[[i]],]$color <- color[i]
}
}
}
res$nodes$value <- res$nodes$members
res$edges$id <- paste0("edge_", 1:nrow( res$edges))
res$nodes$label <- as.character(res$nodes$label)
res$nodes$group[res$nodes$hidden] <- "hidden"
res$nodes$title[res$nodes$hidden] <- NA
res$nodes$value[res$nodes$hidden] <- 0
res$nodes$hidden <- NULL
# res$nodes$label[res$nodes$group %in% "individual" & res$nodes$hidden == FALSE] <- gsub("^(\\n)|(\\n)$", "",
# gsub("", "\\\n", res$nodes$label[res$nodes$group %in% "individual" & res$nodes$hidden == FALSE]))
if(!horizontal){
colnames(res$nodes)[2:3] <- c("y", "x")
}
vis <- visNetwork(res$nodes, res$edges, height = height, width = width, main = main,
submain = submain, footer = footer) %>%
visPhysics(enabled = FALSE) %>%
visInteraction(dragNodes = FALSE, selectConnectedEdges = FALSE) %>%
visEdges(smooth = FALSE, font = list(background = "white")) %>%
visGroups(groupname = "group",
color = list(background = "#D8D8D8", border = "black",
highlight = "black", hover = "black"), shape = "square") %>%
visGroups(groupname = "hidden", color = "rgba(200,200,200,0)", shape = "dot") %>%
visInteraction(hover = TRUE)
if(!horizontal){
vis <- vis %>% visGroups(groupname = "individual",
font = list(size = 200),
color = list(background = "white", border = "white",
highlight = "#e2e9e9", hover = "#e2e9e9"), shape = "box")
} else {
vis <- vis %>% visGroups(groupname = "individual",
font = list(size = 100),
color = list(background = "white", border = "white",
highlight = "#e2e9e9", hover = "#e2e9e9"), shape = "box")
}
if(export){
vis <- vis %>% visExport()
}
if(highlightNearest){
vis <- vis%>%
visOptions(highlightNearest =
list(enabled = TRUE,
degree = list(from = 0, to = 50000),
algorithm = "hierarchical"))
}
vis <- vis%>%sparkline::spk_add_deps()
vis
}
.ctrlDatavisHcl <- function(data){
if(is.null(data)){return(data)}
if(!isTRUE(all.equal("data.frame", class(data)))){
warning("data is coerced to data.frame")
as.data.frame(data)
}else{
data
}
}
.giveDrawNamevisHcl <- function(data, tooltipColumns){
if(!is.null(tooltipColumns)){
names(data)[tooltipColumns]
} else {
NULL
}
}
.giveDataForHcl <- function(data, distColumns){
# columns for compute distance
clas <- unlist(lapply(data , function(X){class(X)[1]}))
clasNum <- which(clas %in% c("numeric", "integer"))
if(!is.null(distColumns)){
indNotNum <- setdiff(distColumns, clasNum)
if(length(indNotNum) > 0){
warning("In distColumns : columns ", paste(indNotNum, collapse = ", "), " not numeric")
}
clasNum <- intersect(distColumns, clasNum)
}
if(length(clasNum) > 0){
dataForHcl <- data[, clasNum, drop = FALSE]
} else {
stop("No numeric or integer columns in data. Can't compute distance.")
}
return(dataForHcl)
}
.manageColorGroupHlc <- function(colorGroups, cutree)
{
if(length(colorGroups) != cutree){
colorGroups <- colorGroups[(0:(cutree-1)%%length(colorGroups))+1]
}
colorGroups
}
# .hlcToPLot <- function(hcl, data, drawNames, minNodeSize, maxNodeSize,
# nodesPopSize, colorEdges, cutree, colorGroups,
# height, width, main, horizontal,
# submain, footer, highlightNearest){
# # Convert data for viz
# res <- .convertHclust(hcl, data, drawNames,
# minNodeSize = minNodeSize, maxNodeSize = maxNodeSize)
# # Make graph
# .makeHlcGraph(res, nodesPopSize, minNodeSize, maxNodeSize,
# colorEdges, cutree, colorGroups,
# height, width, main, horizontal,
# submain, footer, highlightNearest)
# }
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visHclust.R
|
#' Network visualization Hierarchical layout options
#'
#' Network visualization Hierarchical layout options. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a visNetwork object
#'@param enabled : Boolean. Default to TRUE when calling this function. Enable or disable the hierarchical layout.
#'@param levelSeparation : Number. Default to 150. The distance between the different levels.
#'@param nodeSpacing : Number. Default to 100. Minimum distance between nodes on the free axis. This is only for the initial layout. If you enable physics, the node distance there will be the effective node distance.
#'@param treeSpacing : Number. Default to 200. Distance between different trees (independent networks). This is only for the initial layout. If you enable physics, the repulsion model will denote the distance between the trees.
#'@param blockShifting : Boolean. Default to true. Method for reducing whitespace. Can be used alone or together with edge minimization. Each node will check for whitespace and will shift it's branch along with it for as far as it can, respecting the nodeSpacing on any level. This is mainly for the initial layout. If you enable physics, they layout will be determined by the physics. This will greatly speed up the stabilization time though!
#'@param edgeMinimization : Boolean. Default to true. Method for reducing whitespace. Can be used alone or together with block shifting. Enabling block shifting will usually speed up the layout process. Each node will try to move along its free axis to reduce the total length of it's edges. This is mainly for the initial layout. If you enable physics, they layout will be determined by the physics. This will greatly speed up the stabilization time though!
#'@param parentCentralization : Boolean. Default to true. When true, the parents nodes will be centered again after the the layout algorithm has been finished.
#'@param direction : String. Default to 'UD'. The direction of the hierarchical layout. The available options are: UD, DU, LR, RL. To simplify: up-down, down-up, left-right, right-left.
#'@param sortMethod : String. Default to 'hubsize'. The algorithm used to ascertain the levels of the nodes based on the data. The possible options are: hubsize, directed.
#'@param shakeTowards : String. Default to 'roots'. Controls whether in directed layout should all the roots be lined up at the top and their child nodes as close to their roots as possible (roots) or all the leaves lined up at the bottom and their parents as close to their children as possible (leaves, default
#'
#'@examples
#'
#' nodes <- data.frame(id = 1:10)
#' edges <- data.frame(from = round(runif(8)*10), to = round(runif(8)*10))
#'
#' visNetwork(nodes, edges) %>%
#' visHierarchicalLayout()
#'
#' visNetwork(nodes, edges) %>%
#' visHierarchicalLayout(direction = "LR")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visHierarchicalLayout <- function(graph,
enabled = TRUE,
levelSeparation = NULL,
nodeSpacing = NULL,
treeSpacing = NULL,
blockShifting = NULL,
edgeMinimization = NULL,
parentCentralization = NULL,
direction = NULL,
sortMethod = NULL,
shakeTowards = NULL){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
hierarchicalLayout <- list()
hierarchicalLayout$enabled <- enabled
hierarchicalLayout$levelSeparation <- levelSeparation
hierarchicalLayout$nodeSpacing <- nodeSpacing
hierarchicalLayout$treeSpacing <- treeSpacing
hierarchicalLayout$blockShifting <- blockShifting
hierarchicalLayout$edgeMinimization <- edgeMinimization
hierarchicalLayout$parentCentralization <- parentCentralization
hierarchicalLayout$direction <- direction
hierarchicalLayout$sortMethod <- sortMethod
hierarchicalLayout$shakeTowards <- shakeTowards
if(any(class(graph) %in% "visNetwork_Proxy")){
options <- list(layout = list(hierarchical = hierarchicalLayout))
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyOptions",data)
}else{
graph$x$options$layout$hierarchical <- hierarchicalLayout
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visHierarchicalLayout.R
|
#' Render a visNetwork object from an igraph object
#'
#' Render a visNetwork object from an igraph object. \link{toVisNetworkData} transfrom igraph data to visNetwork data.
#' We actually try to keep color, size and label from igraph to visNetwork.
#' \link{visIgraph} plot directly an igraph object in visNetwork, using \link{toVisNetworkData} to extract data, and
#' \link{visIgraphLayout} to compute layout and coordinates before rendering.
#'
#'
#'@param igraph : a igraph object
#'@param idToLabel : Boolean. Default to TRUE. Use id of nodes as label ?
#'@param layout : Character Name of igraph layout function to use. Default to "layout_nicely"
#'@param physics : Boolean. Default to FALSE. Enabled physics on nodes ?
#'@param smooth : Boolean. Default to FALSE. Use smooth edges ?
#'@param type : Character Type of scale from igrah to vis.js. "square" (default) render in a square limit by height. "full" use width and height to scale in a rectangle.
#'@param randomSeed : Number. The nodes are randomly positioned initially. This means that the settled result is different every time. If you provide a random seed manually, the layout will be the same every time.
#'@param layoutMatrix : in case of layout = 'layout.norm'. the 'layout' argument (A matrix with two or three columns, the layout to normalize)
#'@param ... : Adding arguments to layout function
#'
#'@name visNetwork-igraph
#'
#'@examples
#'
#'\dontrun{
#'require(igraph)
#'igraph_network <- graph.famous("Walther")
#'
#'# get data and plot :
#'data <- toVisNetworkData(igraph_network)
#'visNetwork(nodes = data$nodes, edges = data$edges)
#'
#'# or plot directly
#'visIgraph(igraph_network)
#'
#'# change layout
#'visIgraph(igraph_network, layout = "layout_in_circle")
#'
#'# options
#'visIgraph(igraph_network, layout = "layout_in_circle",
#' physics = FALSE, smooth = TRUE)
#'
#'# passing some info
#'g <- graph.star(8)
#'V(g)$color <- c("green", "grey")
#'V(g)$size <- 1:8 *5
#'V(g)$label <- LETTERS[1:8]
#'V(g)$label.cex = seq(1, 2,length.out = 8)
#'V(g)$label.color = "red"
#'visIgraph(g, layout = "layout.circle", idToLabel = FALSE)
#'
#'g <- graph.full(5)
#'E(g)$weight <- runif(ecount(g))
#'E(g)$width <- 1
#'E(g)$color <- "red"
#'E(g)[ weight < 0.5 ]$width <- 4
#'E(g)[ weight < 0.5 ]$color <- "green"
#'E(g)$label <- LETTERS[1:10]
#'E(g)$label.cex = seq(1, 2,length.out = 10)
#'E(g)$label.color = "red"
#'visIgraph(g)
#'
#'# color vertices of the largest component
#'largest_comp <- function(graph) {
#' cl <- components(graph)
#' V(graph)[which.max(cl$csize) == cl$membership]
#'}
#'g <- sample_(gnp(100, 2/100),
#' with_vertex_(size = 3, label = ""),
#' with_graph_(layout = layout_with_fr)
#')
#'giant_v <- largest_comp(g)
#'V(g)$color <- "blue"
#'V(g)[giant_v]$color <- "orange"
#'plot(g)
#'visIgraph(g)
#'}
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @importFrom methods findFunction
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visIgraph <- function(igraph,
idToLabel = TRUE,
layout = "layout_nicely",
physics = FALSE,
smooth = FALSE,
type = "square",
randomSeed = NULL,
layoutMatrix = NULL, ...){
if(!any(class(igraph) %in% "igraph")){
stop("igraph must be a igraph object")
}
if(!type %in% c("square", "full")){
stop("type must be one of 'square' or 'full'")
}
if(!requireNamespace("igraph", quietly = TRUE)){
stop("This function need 'igraph'. Please
install it before.")
}
visdata <- toVisNetworkData(igraph, idToLabel)
directed <- FALSE
if(igraph::is.directed(igraph)){
# if(any(duplicated(edges[, c("from", "to")]))){
#
# }else{
directed <- TRUE
# }
}
graph <- visNetwork(nodes = visdata$nodes, edges = visdata$edges)
if(nrow(visdata$nodes) > 0 | nrow(visdata$edges) > 0){
graph <- graph %>%
visIgraphLayout(layout = layout, type = type, physics = physics,
smooth = smooth, randomSeed = randomSeed,
layoutMatrix = layoutMatrix, ...)
if(directed){
graph <- visEdges(graph, arrows = "to")
}
}
graph
}
#'@rdname visNetwork-igraph
#'@export
toVisNetworkData <- function(igraph,
idToLabel = TRUE){
if(!any(class(igraph) %in% "igraph")){
stop("igraph must be a igraph object")
}
if(!requireNamespace("igraph", quietly = TRUE)){
stop("This function need 'igraph'. Please
install it before.")
}
igraphdata <- igraph::get.data.frame(igraph, what = "both")
nodes <- igraphdata$vertices
if(nrow(nodes) > 0){
if(!"name" %in% colnames(nodes)){
nodes$id <- 1:nrow(nodes)
}else{
colnames(nodes) <- gsub("^name$", "id", colnames(nodes))
}
if("color" %in% colnames(nodes)){
if(class(nodes$color) %in% c("numeric", "integer")){
colnames(nodes) <- gsub("^color$", "group", colnames(nodes))
}
}
if("label.cex" %in% colnames(nodes)){
colnames(nodes) <- gsub("^label.cex$", "font.size", colnames(nodes))
nodes$font.size <- nodes$font.size*40
}
if("label.color" %in% colnames(nodes)){
colnames(nodes) <- gsub("^label.color$", "font.color", colnames(nodes))
}
nodes <- nodes[, c("id", setdiff(colnames(nodes), "id")), drop = FALSE]
if(idToLabel){
nodes$label <- nodes$id
}
} else {
nodes <- data.frame(id = c())
}
edges <- igraphdata$edges
if(nrow(edges) > 0){
if("label.cex" %in% colnames(edges)){
colnames(edges) <- gsub("^label.cex$", "font.size", colnames(edges))
edges$font.size <- edges$font.size*40
}
if("label.color" %in% colnames(edges)){
colnames(edges) <- gsub("^label.color$", "font.color", colnames(edges))
}
} else {
edges = data.frame(from = c(), to = c())
}
list(nodes= nodes, edges = edges)
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visIgraph.R
|
#' Use a igraph layout for compute coordinates & fast rendering
#'
#' Use a igraph layout for compute coordinates and fast rendering.
#' This function affect x and y coordinates to nodes data.frame using a igraph layout,
#' and then render network faster with no stabilization.
#' We set some options as : visNodes(physics = FALSE) &
#' visEdges(smooth = FALSE) & visPhysics(stabilization= FALSE), but you can overwrite
#' them using arguments or by add another call after visIgraphLayout
#'
#'@param graph : a visNetwork object
#'@param layout : Character Name of igraph layout function to use. Default to "layout_nicely"
#'@param physics : Boolean. Default to FALSE. Enabled physics on nodes ?
#'@param smooth : Boolean. Default to FALSE. Use smooth edges ?
#'@param type : Character Type of scale from igrah to vis.js. "square" (default) render in a square limit by height. "full" use width and height to scale in a rectangle.
#'@param randomSeed : Number. The nodes are randomly positioned initially. This means that the settled result is different every time. If you provide a random seed manually, the layout will be the same every time.
#'@param layoutMatrix : in case of layout = 'layout.norm'. the 'layout' argument (A matrix with two or three columns, the layout to normalize)
#'@param ... : Adding arguments to layout function
#'
#'@examples
#'
#'\dontrun{
#'nnodes <- 200
#'nnedges <- 400
#'
#'nodes <- data.frame(id = 1:nnodes)
#'edges <- data.frame(from = sample(1:nnodes, nnedges, replace = T),
#' to = sample(1:nnodes, nnedges, replace = T))
#'
#'# with default layout
#'visNetwork(nodes, edges) %>%
#' visIgraphLayout()
#'
#'# use full space
#'visNetwork(nodes, edges) %>%
#' visIgraphLayout(type = "full")
#'
#'# in circle ?
#'visNetwork(nodes, edges) %>%
#' visIgraphLayout(layout = "layout_in_circle") %>%
#' visOptions(highlightNearest = list(enabled = T, hover = T),
#' nodesIdSelection = T)
#'
#'# keep physics with smooth curves ?
#'visNetwork(nodes, edges) %>%
#' visIgraphLayout(physics = TRUE, smooth = TRUE)
#'
#'# fix randomSeed to keep position
#'visNetwork(nodes, edges) %>%
#' visIgraphLayout(randomSeed = 123)
#'
#'visNetwork(nodes, edges) %>%
#' visIgraphLayout(randomSeed = 123)
#'
#'# layout_with_sugiyama
#'nodes <- data.frame(id = 1:5)
#'edges <- data.frame(from = c(1, 2, 2, 4), to = c(2, 3, 4, 5))
#'
#'visNetwork(nodes, edges) %>%
#' visIgraphLayout(layout = "layout_with_sugiyama", layers = c(1, 2, 3, 3, 4))
#'
#'visNetwork(nodes, edges) %>%
#' visIgraphLayout(layout = "layout_with_sugiyama")
#'
#'}
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @importFrom utils getAnywhere
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visIgraphLayout <- function(graph,
layout = "layout_nicely",
physics = FALSE,
smooth = FALSE,
type = "square",
randomSeed = NULL,
layoutMatrix = NULL, ...){
if(any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visIgraphLayout with visNetworkProxy object")
}
if(!any(class(graph) %in% "visNetwork")){
stop("graph must be a visNetwork object")
}
if(!all(c("nodes", "edges") %in% names(graph$x))){
stop("Need 'nodes' and 'edges' informations on network")
}
if(!type %in% c("square", "full")){
stop("type must be one of 'square' or 'full'")
}
if(!requireNamespace("igraph", quietly = TRUE)){
stop("This function need 'igraph' package to compute layout. Please
install it before.")
}
ctrl <- getAnywhere(layout)
if(length(ctrl$objs) == 0){
stop("Can't find '", layout, "' function. Please verify it")
}
if(!is.function(ctrl$objs[[1]])){
stop("'", layout, "' must be a function.")
}
igraphlayout <- list(type = type)
ig <- igraph::graph_from_data_frame(graph$x$edges[, c("from", "to")], directed = TRUE,
vertices = graph$x$nodes[, c("id", setdiff(names(graph$x$nodes), "id"))])
if(!is.null(randomSeed)){
set.seed(randomSeed)
}
if("layout.norm" %in% layout){
if (is.null(layoutMatrix)) {
stop("'layout.norm' requires a layout argument (a matrix with two or three columns), passed by layoutMatrix argument")
}
coord <- ctrl$objs[[1]](layout = layoutMatrix, ...)
} else if("layout_with_sugiyama" %in% layout){
coord <- ctrl$objs[[1]](graph = ig, ...)$layout
coord[, 2] <- max(coord[, 2]) - coord[, 2] + 1
} else {
coord <- ctrl$objs[[1]](graph = ig, ...)
}
graph$x$nodes$x <- coord[, 1]
graph$x$nodes$y <- coord[, 2]
to <- c(-1, 1)
from <- range(graph$x$nodes$x, na.rm = TRUE, finite = TRUE)
if(length(unique(from)) > 1){
graph$x$nodes$x <- (graph$x$nodes$x - from[1])/diff(from) * diff(to) + to[1]
}
from <- range(graph$x$nodes$y, na.rm = TRUE, finite = TRUE)
if(length(unique(from)) > 1){
graph$x$nodes$y <- (graph$x$nodes$y - from[1])/diff(from) * diff(to) + to[1]
}
# graph$x$nodes$physics = physics
graph$x$igraphlayout <- igraphlayout
graph %>% visNodes(physics = physics) %>%
visEdges(smooth = smooth) %>% visPhysics(stabilization = FALSE)
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visIgraphLayout.R
|
#' Network visualization interaction
#'
#' Network visualization interaction. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a visNetwork object
#'@param dragNodes : Boolean. Default to true. When true, the nodes that are not fixed can be dragged by the user.
#'@param dragView : Boolean. Default to true. When true, the view can be dragged around by the user.
#'@param hideEdgesOnDrag : Boolean. Default to false. When true, the edges are not drawn when dragging the view. This can greatly speed up responsiveness on dragging, improving user experience.
#'@param hideEdgesOnZoom : Boolean. Default to false. When true, the edges are not drawn when zooming the view. This can greatly speed up responsiveness on zooming, improving user experience.
#'@param hideNodesOnDrag : Boolean. Default to false. When true, the nodes are not drawn when dragging the view. This can greatly speed up responsiveness on dragging, improving user experience.
#'@param hover : Boolean. Default to false. When true, the nodes use their hover colors when the mouse moves over them.
#'@param hoverConnectedEdges : Boolean. Default to true. When true, on hovering over a node, it's connecting edges are highlighted.
#'@param keyboard : Just a Boolean, or a named list. When true, the keyboard shortcuts are enabled with the default settings. For further customization, you can supply an object.
#'\itemize{
#' \item{"enabled"}{ : Boolean. Default to false. Toggle the usage of the keyboard shortcuts. If this option is not defined, it is set to true if any of the properties in this object are defined.}
#' \item{"speed"}{ : a named list
#' \itemize{
#' \item{"x"}{ : Number. Default to 1. This defines the speed of the camera movement in the x direction when using the keyboard navigation.}
#' \item{"y"}{ : Number. Default to 1. This defines the speed of the camera movement in the y direction when using the keyboard navigation.}
#' \item{"zoom"}{ : Number. Default to 0.02. This defines the zoomspeed when using the keyboard navigation.Number 0.02 This defines the zoomspeed when using the keyboard navigation.}
#' }
#' }
#' \item{"bindToWindow"}{ : Boolean. Default to true. If this is true, global keyboard events will be used. If it is false, the keyboard events are only used when the network is active. It is activated on mouseOver automatically.}
#'}
#'@param multiselect : Boolean. Default to false. When true, a longheld click (or touch) as well as a control-click will add to the selection.
#'@param navigationButtons : Boolean. Default to false. When true, navigation buttons are drawn on the network canvas. These are HTML buttons and can be completely customized using CSS.
#'@param selectable : Boolean. Default to true When true, the nodes and edges can be selected by the user.
#'@param selectConnectedEdges : Boolean. Default to true. When true, on selecting a node, its connecting edges are highlighted.
#'@param tooltipDelay : Number. Default to 300. When nodes or edges have a defined 'title' field, this can be shown as a pop-up tooltip. The tooltip itself is an HTML element that can be fully styled using CSS. The delay is the amount of time in milliseconds it takes before the tooltip is shown.
#'@param tooltipStay : Number. Default to 300. This is the amount of time in milliseconds it takes before the tooltip is hidden.
#'@param tooltipStyle : Character. HTML style of tooltip. You must use 'position: fixed;visibility:hidden;'.
#'@param zoomView : Boolean. Default to true. When true, the user can zoom in.
#'@param zoomSpeed : Number. Default to 1. How fast/rough or slow/precise zooming is.
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'
#'nodes <- data.frame(id = 1:10,
#' title = '<a target="_blank" href="https://github.com/datastorm-open/visNetwork">github</a>')
#'edges <- data.frame(from = round(runif(8)*10), to = round(runif(8)*10))
#'
#'# custom tooltip
#'
#'# default value : 'position: fixed;visibility:hidden;padding: 5px;font-family: verdana;
#'# font-size:14px;font-color:#000000;background-color: #f5f4ed;-moz-border-radius: 3px;*
#'# -webkit-border-radius: 3px;border-radius: 3px; border: 1px solid #808074;
#'# box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2);max-width:400px;word-break: break-all'
#'
#'visNetwork(nodes, edges) %>%
#' visInteraction(tooltipStyle = 'position: fixed;visibility:hidden;padding: 5px;white-space: nowrap;
#' font-family: cursive;font-size:18px;font-color:purple;background-color: red;')
#'
#' nodes <- data.frame(id = 1:3)
#' edges <- data.frame(from = c(1,2), to = c(1,3))
#'
#'# frozen network
#'visNetwork(nodes, edges) %>%
#' visInteraction(dragNodes = FALSE, dragView = FALSE, zoomView = FALSE)
#'
#'visNetwork(nodes, edges) %>%
#' visInteraction(hideEdgesOnDrag = TRUE)
#'
#'visNetwork(nodes, edges) %>%
#' visInteraction(hover = TRUE)
#'
#'# navigation button
#'visNetwork(nodes, edges) %>%
#' visInteraction(navigationButtons = TRUE)
#'
#'visNetwork(nodes, edges) %>%
#' visInteraction(selectConnectedEdges = FALSE)
#'
#'visNetwork(nodes, edges) %>%
#' visInteraction(multiselect = TRUE)
#'
#'visNetwork(nodes, edges) %>%
#' visInteraction(keyboard = TRUE)
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visInteraction <- function(graph,
dragNodes = NULL,
dragView = NULL,
hideEdgesOnDrag = NULL,
hideEdgesOnZoom = NULL,
hideNodesOnDrag = NULL,
hover = NULL,
hoverConnectedEdges = NULL,
keyboard = NULL,
multiselect = NULL,
navigationButtons = NULL,
selectable = NULL,
selectConnectedEdges = NULL,
tooltipDelay = NULL,
tooltipStay = 300,
tooltipStyle = NULL,
zoomView = NULL,
zoomSpeed = 1){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
interaction <- list()
interaction$dragNodes <- dragNodes
interaction$dragView <- dragView
interaction$hideEdgesOnDrag <- hideEdgesOnDrag
interaction$hideEdgesOnZoom <- hideEdgesOnZoom
interaction$hideNodesOnDrag <- hideNodesOnDrag
interaction$hover <- hover
interaction$hoverConnectedEdges <- hoverConnectedEdges
interaction$keyboard <- keyboard
interaction$multiselect <- multiselect
interaction$navigationButtons <- navigationButtons
interaction$selectable <- selectable
interaction$selectConnectedEdges <- selectConnectedEdges
interaction$tooltipDelay <- tooltipDelay
interaction$zoomView <-zoomView
interaction$zoomSpeed <- zoomSpeed
if(any(class(graph) %in% "visNetwork_Proxy")){
options <- list(interaction = interaction)
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyOptions",data)
}else{
if(length(interaction) > 0){
graph$x$options$interaction <- mergeLists(graph$x$options$interaction, interaction)
}
if(is.null(tooltipStyle)){
tooltipStyle <- 'position: fixed;visibility:hidden;padding: 5px;white-space: nowrap;font-family: verdana;font-size:14px;font-color:#000000;background-color: #f5f4ed;-moz-border-radius: 3px;-webkit-border-radius: 3px;border-radius: 3px;border: 1px solid #808074;box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2);'
}
x <- list(tooltipStay = tooltipStay, tooltipStyle = tooltipStyle)
graph$x <- mergeLists(graph$x, x)
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visInteraction.R
|
#' Network visualization layout options
#'
#' Network visualization layout options. For full documentation, have a look at \link{visDocumentation}.
#'
#' @param graph : a visNetwork object
#' @param randomSeed : Number. When NOT using the hierarchical layout, the nodes are randomly positioned initially. This means that the settled result is different every time. If you provide a random seed manually, the layout will be the same every time. Ideally you try with an undefined seed, reload until you are happy with the layout and use the getSeed() method to ascertain the seed.
#' @param improvedLayout : Boolean. Default to true. When enabled, the network will use the Kamada Kawai algorithm for initial layout. For networks larger than 100 nodes, clustering will be performed automatically to reduce the amount of nodes. This can greatly improve the stabilization times. If the network is very interconnected (no or few leaf nodes), this may not work and it will revert back to the old method. Performance will be improved in the future.
#' @param clusterThreshold : Number. Default to 150. Cluster threshold to which improvedLayout applies.
#' @param hierarchical : Boolean. Default to false. When true, the layout engine positions the nodes in a hierarchical fashion using default settings. For customization you can use \link{visHierarchicalLayout}
#'
#' @examples
#'
#' nodes <- data.frame(id = 1:10)
#' edges <- data.frame(from = round(runif(8)*10), to = round(runif(8)*10))
#'
#' # fix seed, so you retrieve same network each time...!
#' visNetwork(nodes, edges) %>%
#' visLayout(randomSeed = 123)
#'
#' visNetwork(nodes, edges) %>%
#' visLayout(randomSeed = 123)
#'
#' # hierarchical
#' visNetwork(nodes, edges) %>%
#' visLayout(hierarchical = TRUE)
#'
#' visNetwork(nodes, edges) %>%
#' visHierarchicalLayout(direction = "LR")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visLayout <- function(graph,
randomSeed = NULL,
improvedLayout = NULL,
clusterThreshold = NULL,
hierarchical = NULL){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
layout <- list()
layout$randomSeed <- randomSeed
layout$improvedLayout <- improvedLayout
layout$clusterThreshold <- clusterThreshold
layout$hierarchical <- hierarchical
if(any(class(graph) %in% "visNetwork_Proxy")){
options <- list(layout = layout)
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyOptions",data)
}else{
if("layout"%in%names(graph$x$options)){
graph$x$options$layout <- mergeLists(graph$x$options$layout, layout)
}else{
graph$x$options$layout <- layout
}
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visLayout.R
|
#' Add a legend on a visNetwork object
#'
#' Add a legend on a visNetwork object
#'
#' @param graph : a visNetwork object
#' @param enabled : Boolean. Default to TRUE.
#' @param useGroups : use groups options in legend ? Default to TRUE.
#' @param addNodes : a data.frame or a list for adding custom node(s)
#' @param addEdges : a data.frame or a list for adding custom edges(s)
#' @param width : Number, in [0,...,1]. Default to 0.2
#' @param position : one of "left" (Default) or "right"
#' @param main : For add a title. Character or a named list.
#' \itemize{
#' \item{"text"}{ : Character. Title.}
#' \item{"style"}{ : Optional. Character. HTML style of title. Default to 'font-family:Georgia, Times New Roman, Times, serif;font-weight:bold;font-size:14px;text-align:center;'.}
#' }
#' @param ncol : Divide legend in multiple columns ? Default to 1
#' @param stepX : Experimental. Can use to control space between nodes. Default to 100
#' @param stepY : Experimental. Can use to control space between nodes. Default to 100
#' @param zoom : Boolean. Enable zoom on legend ? Default to TRUE
#'
#' @examples
#'
#' # minimal example
#' nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
#' edges <- data.frame(from = c(1,2), to = c(2,3))
#'
#' # default, on group
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", color = "red") %>%
#' visGroups(groupname = "B", color = "lightblue") %>%
#' visLegend()
#'
#' \dontrun{
#' # on group, adding options
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", color = "red") %>%
#' visGroups(groupname = "B", color = "lightblue") %>%
#' visLegend(width = 0.1, position = "right", main = "Legend")
#'
#' # css on main
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", color = "red") %>%
#' visGroups(groupname = "B", color = "lightblue") %>%
#' visLegend(main = list(text = "Custom Legend",
#' style = "font-family:Comic Sans MS;color:#ff0000;font-size:12px;text-align:center;"))
#'
#' # passing custom nodes and/or edges
#' lnodes <- data.frame(label = c("Group A", "Group B"),
#' shape = c( "ellipse"), color = c("red", "lightblue"),
#' title = "Informations")
#'
#' ledges <- data.frame(color = c("lightblue", "red"),
#' label = c("reverse", "depends"), arrows =c("to", "from"),
#' font.align = "top")
#'
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", color = "red") %>%
#' visGroups(groupname = "B", color = "lightblue") %>%
#' visLegend(addNodes = lnodes, addEdges = ledges, useGroups = FALSE)
#'
#' # divide in columns
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", color = "red") %>%
#' visGroups(groupname = "B", color = "lightblue") %>%
#' visLegend(addNodes = lnodes, useGroups = TRUE, ncol = 2)
#'
#' # for more complex option, you can use a list(of list...)
#' # or a data.frame with specific notaion
#'
#' nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
#' edges <- data.frame(from = c(1,2), to = c(2,3))
#'
#' # using a list
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", shape = "icon", icon = list(code = "f0c0", size = 75)) %>%
#' visGroups(groupname = "B", shape = "icon", icon = list(code = "f007", color = "red")) %>%
#' addFontAwesome() %>%
#' visLegend(addNodes = list(
#' list(label = "Group", shape = "icon", icon = list(code = "f0c0", size = 25)),
#' list(label = "User", shape = "icon", icon = list(code = "f007", size = 50, color = "red"))
#' ),
#' addEdges = data.frame(label = "link"), useGroups = FALSE)
#'
#' # using a data.frame
#' addNodes <- data.frame(label = c("Group", "User"), shape = "icon",
#' icon.code = c("f0c0", "f007"), icon.size = c(25, 50), icon.color = c(NA, "red"))
#'
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", shape = "icon", icon = list(code = "f0c0", size = 75)) %>%
#' visGroups(groupname = "B", shape = "icon", icon = list(code = "f007", color = "red")) %>%
#' addFontAwesome() %>%
#' visLegend(addNodes = addNodes,
#' addEdges = data.frame(label = "link"), useGroups = FALSE)
#'
#' }
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @import htmlwidgets
#'
#' @export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visLegend <- function(graph,
enabled = TRUE,
useGroups = TRUE,
addNodes = NULL,
addEdges = NULL,
width = 0.2,
position = "left",
main = NULL,
ncol = 1,
stepX = 100,
stepY = 100,
zoom = TRUE){
stopifnot(is.numeric(ncol))
stopifnot(is.numeric(stepX))
stopifnot(is.numeric(stepY))
if(any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visLegend with visNetworkProxy object")
}
if(!any(class(graph) %in% "visNetwork")){
stop("graph must be a visNetwork object")
}
if(enabled){
legend <- list()
if(!(width >= 0 & width <= 1)){
stop("'width' must be between 0 and 1")
}
legend$width <- width
if(!is.logical(useGroups)){
stop("useGroups must be logical (TRUE/FALSE)")
}
legend$useGroups <- useGroups
if(!position%in%c("left", "right")){
stop("position must be one of 'left' or 'right'")
}
legend$position <- position
if(!ncol >= 1){
stop("ncol must be an integer >= 1")
}
legend$ncol <- ncol
legend$stepX <- stepX
legend$stepY <- stepY
legend$zoom <- zoom
if(!is.null(addEdges)){
legend$edges <- addEdges
if(is.data.frame(addEdges)){
legend$edgesToDataframe <- TRUE
}else if(is.list(addEdges)){
legend$edgesToDataframe <- TRUE
}else{
stop("addEdges must be a data.frame or a list")
}
}
if(!is.null(addNodes)){
legend$nodes <- addNodes
if(is.data.frame(addNodes)){
legend$nodesToDataframe <- TRUE
}else if(is.list(addNodes)){
legend$nodesToDataframe <- FALSE
}else{
stop("addNodes must be a data.frame or a list")
}
}
# main
if(!is.null(main)){
if(is.list(main)){
if(any(!names(main)%in%c("text", "style"))){
stop("Invalid 'main' argument")
}
if(!"text"%in%names(main)){
stop("Needed a 'text' value using a list for 'main'")
}
if(!"style"%in%names(main)){
main$style <- 'font-family:Georgia, Times New Roman, Times, serif;font-weight:bold;font-size:14px;text-align:center;'
}
}else if(!inherits(main, "character")){
stop("Invalid 'main' argument. Not a character")
}else {
main <- list(text = main,
style = 'font-family:Georgia, Times New Roman, Times, serif;font-weight:bold;font-size:14px;text-align:center;')
}
legend$main <- main
}
graph$x$legend <- legend
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visLegend.R
|
#' Network visualization moveNode method
#'
#' For use moveNode() method in a shiny app. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param id : a node id
#'@param x : Number. x position, in canvas space
#'@param y : Number. y position, in canvas space
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visMoveNode <- function(graph, id, x, y){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visMoveNode with visNetwork object. Only within shiny & using visNetworkProxy")
}
stopifnot(length(id) == 1)
data <- list(id = graph$id, nodeId = id, x = x, y = y)
graph$session$sendCustomMessage("visShinyMoveNode", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visMoveNode.R
|
#' Function to nearest nodes of a target node, with shiny only.
#'
#' Function to nearest nodes of a target node, with shiny only.
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param target : name of shiny input returning target node id
#' @param maxpoints : Number of nearest nodes. Default to 5
#' @param addDist : If TRUE, add a column named dist_ that contains the distance from the coordinate to the point, in pixels.
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visNearestNodes <- function(graph, target, maxpoints = 5, addDist = T){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visGetNodes with visNetwork object. Only within shiny & using visNetworkProxy")
}
force(target)
visNetworkProxy(graph$id) %>%
visGetNodes(input = graph$session$ns("tmp_nearest_nodes"))
current_nodes <- graph$session$input$tmp_nearest_nodes
if(is.list(current_nodes)){
current_nodes <- rbind.fill.network(lapply(current_nodes, function(x){data.frame(t(unlist(x)))}))
} else{
current_nodes <- NULL
}
res <- NULL
if(!is.null(current_nodes)){
target_row <- which(current_nodes$id %in% target)
if(length(target_row) > 0){
current_nodes[, "x"] <- as.numeric(as.character(current_nodes[, "x"]))
current_nodes[, "y"] <- as.numeric(as.character(current_nodes[, "y"]))
current_nodes$dist_ <- sqrt((current_nodes[, "x"] - current_nodes[target_row, "x"])^2 +
(current_nodes[, "y"] - current_nodes[target_row, "y"])^2)
res <- current_nodes[-target_row, ]
res <- res[order(res$dist_), ]
res <- res[1:min(maxpoints, nrow(res)), ]
if(!addDist){
res$dist_ <- NULL
}
}
}
res
}
allocate_column_network <- function (example, nrows, dfs, var)
{
a <- attributes(example)
type <- typeof(example)
class <- a$class
isList <- is.recursive(example)
a$names <- NULL
a$class <- NULL
if (is.data.frame(example)) {
stop("Data frame column '", var, "' not supported by rbind.fill")
}
if (is.array(example)) {
if (length(dim(example)) > 1) {
if ("dimnames" %in% names(a)) {
a$dimnames[1] <- list(NULL)
if (!is.null(names(a$dimnames)))
names(a$dimnames)[1] <- ""
}
df_has <- vapply(dfs, function(df) var %in% names(df),
FALSE)
dims <- unique(lapply(dfs[df_has], function(df) dim(df[[var]])[-1]))
if (length(dims) > 1)
stop("Array variable ", var, " has inconsistent dims")
a$dim <- c(nrows, dim(example)[-1])
length <- prod(a$dim)
}
else {
a$dim <- NULL
a$dimnames <- NULL
length <- nrows
}
}
else {
length <- nrows
}
if (is.factor(example)) {
df_has <- vapply(dfs, function(df) var %in% names(df),
FALSE)
isfactor <- vapply(dfs[df_has], function(df) is.factor(df[[var]]),
FALSE)
if (all(isfactor)) {
levels <- unique(unlist(lapply(dfs[df_has], function(df) levels(df[[var]]))))
a$levels <- levels
handler <- "factor"
}
else {
type <- "character"
handler <- "character"
class <- NULL
a$levels <- NULL
}
}
else if (inherits(example, "POSIXt")) {
tzone <- attr(example, "tzone")
class <- c("POSIXct", "POSIXt")
type <- "double"
handler <- "time"
}
else {
handler <- type
}
column <- vector(type, length)
if (!isList) {
column[] <- NA
}
attributes(column) <- a
assignment <- make_assignment_call_network(length(a$dim))
setter <- switch(handler, character = function(rows, what) {
what <- as.character(what)
eval(assignment)
}, factor = function(rows, what) {
what <- match(what, levels)
eval(assignment)
}, time = function(rows, what) {
what <- as.POSIXct(what, tz = tzone)
eval(assignment)
}, function(rows, what) {
eval(assignment)
})
getter <- function() {
class(column) <<- class
column
}
list(set = setter, get = getter)
}
output_template_network <- function (dfs, nrows)
{
vars <- unique(unlist(lapply(dfs, base::names)))
output <- vector("list", length(vars))
names(output) <- vars
seen <- rep(FALSE, length(output))
names(seen) <- vars
for (df in dfs) {
matching <- intersect(names(df), vars[!seen])
for (var in matching) {
output[[var]] <- allocate_column_network(df[[var]], nrows,
dfs, var)
}
seen[matching] <- TRUE
if (all(seen))
break
}
list(setters = lapply(output, `[[`, "set"), getters = lapply(output,
`[[`, "get"))
}
make_assignment_call_network <- function (ndims)
{
assignment <- quote(column[rows] <<- what)
if (ndims >= 2) {
assignment[[2]] <- as.call(c(as.list(assignment[[2]]),
rep(list(quote(expr = )), ndims - 1)))
}
assignment
}
make_names_network <- function (x, prefix = "X")
{
nm <- names(x)
if (is.null(nm)) {
nm <- rep.int("", length(x))
}
n <- sum(nm == "", na.rm = TRUE)
nm[nm == ""] <- paste(prefix, seq_len(n), sep = "")
nm
}
quickdf_network <- function (list)
{
rows <- unique(unlist(lapply(list, NROW)))
stopifnot(length(rows) == 1)
names(list) <- make_names_network(list, "X")
class(list) <- "data.frame"
attr(list, "row.names") <- c(NA_integer_, -rows)
list
}
rbind.fill.network<- function (...)
{
dfs <- list(...)
if (length(dfs) == 0)
return()
if (is.list(dfs[[1]]) && !is.data.frame(dfs[[1]])) {
dfs <- dfs[[1]]
}
if (length(dfs) == 0)
return()
if (length(dfs) == 1)
return(dfs[[1]])
is_df <- vapply(dfs, is.data.frame, logical(1))
if (any(!is_df)) {
stop("All inputs to rbind.fill must be data.frames",
call. = FALSE)
}
rows <- unlist(lapply(dfs, .row_names_info, 2L))
nrows <- sum(rows)
ot <- output_template_network(dfs, nrows)
setters <- ot$setters
getters <- ot$getters
if (length(setters) == 0) {
return(as.data.frame(matrix(nrow = nrows, ncol = 0)))
}
pos <- matrix(c(cumsum(rows) - rows + 1, rows), ncol = 2)
for (i in seq_along(rows)) {
rng <- seq(pos[i, 1], length = pos[i, 2])
df <- dfs[[i]]
for (var in names(df)) {
setters[[var]](rng, df[[var]])
}
}
quickdf_network(lapply(getters, function(x) x()))
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visNearestNodes.R
|
#' Network visualization
#'
#' Network visualization using vis.js library. For full documentation, have a look at \link{visDocumentation}.
#'
#' @param nodes : data.frame or a list with nodes informations. Needed at least column "id". See \link{visNodes}
#' \itemize{
#' \item{"id"}{ : id of the node, needed in edges information}
#' \item{"label"}{ : label of the node}
#' \item{"group"}{ : group of the node. Groups can be configure with \link{visGroups}}
#' \item{"value"}{ : size of the node}
#' \item{"title"}{ : tooltip of the node}
#' \item{...}{}
#'}
#'
#' @param edges : data.frame or a list with edges informations. Needed at least columns "from" and "to". See \link{visEdges}
#' \itemize{
#' \item{"from"}{ : node id of begin of the edge}
#' \item{"to"}{ : node id of end of the edge}
#' \item{"label"}{ : label of the edge}
#' \item{"value"}{ : size of the node}
#' \item{"title"}{ : tooltip of the node}
#' \item{...}{}
#'}
#'
#' @param dot : Character DOT language.
#'
#' @param gephi : Json export gephi path file.
#'
#' @param width : Width (optional, defaults to automatic sizing)
#'
#' @param height : Height (optional, defaults to automatic sizing)
#'
#'@param main : For add a title. Character or a named list.
#'\itemize{
#' \item{"text"}{ : Character. Title.}
#' \item{"style"}{ : Optional. Character. HTML style of title. Default to 'font-family:Georgia, Times New Roman, Times, serif;font-weight:bold;font-size:20px;text-align:center;'.}
#'}
#'
#'@param submain : For add a subtitle. Character or a named list.
#'\itemize{
#' \item{"text"}{ : Character. Subtitle.}
#' \item{"style"}{ : Optional. Character. HTML style of submain. Default to 'font-family:Georgia, Times New Roman, Times, serif;font-size:12px;text-align:center;'.}
#'}
#'
#'@param footer : For add a footer. Character or a named list.
#'\itemize{
#' \item{"text"}{ : Character. footer.}
#' \item{"style"}{ : Optional. Character. HTML style of footer. Default to 'font-family:Georgia, Times New Roman, Times, serif;font-size:12px;text-align:center;'.}
#'}
#'
#'@param background : Background color. Default to 'rgba(0, 0, 0, 0)' (transparent). Can be a valid color name ("red"), a HEX value ("#ff0000") or rgb/rgba ("rgb(255,0,0)")
#'
#' @param ... : Don't use.
#'
#' @examples
#'
#' # minimal example
#' nodes <- data.frame(id = 1:3)
#' edges <- data.frame(from = c(1,2), to = c(1,3))
#'
#' visNetwork(nodes, edges)
#'
#' \dontrun{
#' # add a title
#' visNetwork(nodes, edges, main = "visNetwork minimal example")
#' visNetwork(nodes, edges, main = list(text = "visNetwork minimal example",
#' style = "font-family:Comic Sans MS;color:#ff0000;font-size:15px;text-align:center;"))
#'
#' # and subtitle and footer
#' visNetwork(nodes, edges, main = "visNetwork minimal example",
#' submain = "For add a subtitle", footer = "Fig.1 minimal example")
#'
#' # change background color
#' visNetwork(nodes, edges, background = "black")
#'
#' # customization adding more variables (see visNodes and visEdges)
#' nodes <- data.frame(id = 1:10,
#' label = paste("Node", 1:10), # labels
#' group = c("GrA", "GrB"), # groups
#' value = 1:10, # size
#' shape = c("square", "triangle", "box", "circle", "dot", "star",
#' "ellipse", "database", "text", "diamond"), # shape
#' title = paste0("<p><b>", 1:10,"</b><br>Node !</p>"), # tooltip
#' color = c("darkred", "grey", "orange", "darkblue", "purple"),# color
#' shadow = c(FALSE, TRUE, FALSE, TRUE, TRUE)) # shadow
#'
#' edges <- data.frame(from = sample(1:10,8), to = sample(1:10, 8),
#' label = paste("Edge", 1:8), # labels
#' length = c(100,500), # length
#' arrows = c("to", "from", "middle", "middle;to"), # arrows
#' dashes = c(TRUE, FALSE), # dashes
#' title = paste("Edge", 1:8), # tooltip
#' smooth = c(FALSE, TRUE), # smooth
#' shadow = c(FALSE, TRUE, FALSE, TRUE)) # shadow
#'
#' visNetwork(nodes, edges)
#'
#' # use more complex configuration :
#' # when it's a list, you can use data.frame with specific notation like this
#' nodes <- data.frame(id = 1:3, color.background = c("red", "blue", "green"),
#' color.highlight.background = c("red", NA, "red"), shadow.size = c(5, 10, 15))
#' edges <- data.frame(from = c(1,2), to = c(1,3),
#' label = LETTERS[1:2], font.color =c ("red", "blue"), font.size = c(10,20))
#'
#' visNetwork(nodes, edges)
#'
#' # highlight nearest
#' nodes <- data.frame(id = 1:15, label = paste("Label", 1:15),
#' group = sample(LETTERS[1:3], 15, replace = TRUE))
#'
#' edges <- data.frame(from = trunc(runif(15)*(15-1))+1,
#' to = trunc(runif(15)*(15-1))+1)
#'
#' visNetwork(nodes, edges) %>% visOptions(highlightNearest = TRUE)
#'
#' # try an id node selection
#' visNetwork(nodes, edges) %>%
#' visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)
#'
#' # or add a selection on another column
#' visNetwork(nodes, edges) %>%
#' visOptions(selectedBy = "group")
#'
#' nodes$sel <- sample(c("sel1", "sel2"), nrow(nodes), replace = TRUE)
#' visNetwork(nodes, edges) %>%
#' visOptions(selectedBy = "sel")
#'
#' # add legend
#' visNetwork(nodes, edges) %>% visLegend()
#'
#' # directed network
#' visNetwork(nodes, edges) %>%
#' visEdges(arrows = 'from', scaling = list(min = 2, max = 2))
#'
#' # custom navigation
#' visNetwork(nodes, edges) %>%
#' visInteraction(navigationButtons = TRUE)
#'
#' # data Manipulation
#' visNetwork(nodes, edges) %>% visOptions(manipulation = TRUE)
#'
#' # Hierarchical Layout
#' visNetwork(nodes, edges) %>% visHierarchicalLayout()
#'
#' # freeze network
#' visNetwork(nodes, edges) %>%
#' visInteraction(dragNodes = FALSE, dragView = FALSE, zoomView = FALSE)
#'
#' # use fontAwesome icons using groups or nodes options
#' # font-awesome is not part of dependencies. use addFontAwesome() if needed
#'
#' nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
#' edges <- data.frame(from = c(1,2), to = c(2,3))
#'
#' visNetwork(nodes, edges) %>%
#' visGroups(groupname = "A", shape = "icon", icon = list(code = "f0c0", size = 75)) %>%
#' visGroups(groupname = "B", shape = "icon", icon = list(code = "f007", color = "red")) %>%
#' addFontAwesome()
#'
#' nodes <- data.frame(id = 1:3)
#' edges <- data.frame(from = c(1,2), to = c(1,3))
#'
#' visNetwork(nodes, edges) %>%
#' visNodes(shape = "icon", icon = list( face ='FontAwesome', code = "f0c0")) %>%
#' addFontAwesome()
#'
#' # Save a network
#'
#' network <- visNetwork(nodes, edges) %>%
#' visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE,
#' manipulation = TRUE) %>% visLegend()
#'
#' network %>% visSave(file = "network.html")
#' # same as
#' visSave(network, file = "network.html")
#'
#'
#' # Export as png/jpeg (shiny or browser only)
#' visNetwork(nodes, edges) %>%
#' visExport()
#'
#'
#' # DOT language
#' visNetwork(dot = 'dinetwork {1 -> 1 -> 2; 2 -> 3; 2 -- 4; 2 -> 1 }')
#'
#' # gephi json file
#'
#' visNetwork(gephi = 'WorldCup2014.json') %>% visPhysics(stabilization = FALSE, barnesHut = list(
#' gravitationalConstant = -10000,
#' springConstant = 0.002,
#' springLength = 150
#' ))
#'}
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} for play with network using shiny,
#'\link{visTree} to visualize CART rpart tree, \link{visNetworkEditor} to edit your network,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @import htmlwidgets
#'
#' @importFrom jsonlite fromJSON
#'
#' @export
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visNetwork <- function(nodes = NULL, edges = NULL, dot = NULL, gephi = NULL,
width = NULL, height = NULL, main = NULL, submain = NULL,
footer = NULL, background = 'rgba(0, 0, 0, 0)', ...) {
if(is.null(nodes) & is.null(edges) & is.null(dot) & is.null(gephi)){
stop("Must 'dot' data, or 'gephi' data, or 'nodes' and 'edges' data.")
}
if(!is.null(nodes)){
if(any(class(nodes)%in%c("tbl_df", "tbl", "data.table"))){
nodes <- data.frame(nodes)
}
if(is.data.frame(nodes)){
nodesToDataframe <- TRUE
# unique id
if(anyDuplicated(nodes$id)){
stop("nodes must have unique ids")
}
}else if(is.list(nodes)){
nodesToDataframe <- FALSE
}else{
stop("nodes must be a data.frame or a list")
}
} else {
nodesToDataframe <- FALSE
}
if(!is.null(edges)){
if(any(class(edges)%in%c("tbl_df", "tbl", "data.table"))){
edges <- data.frame(edges)
}
if(is.data.frame(edges)){
edgesToDataframe <- TRUE
}else if(is.list(edges)){
edgesToDataframe <- FALSE
}else{
stop("edges must be a data.frame or a list")
}
} else {
edgesToDataframe <- FALSE
}
if(is.data.frame(nodes) & is.data.frame(edges)){
rm_edges <- which(!(edges$from %in% nodes$id & edges$to %in% nodes$id))
if(length(rm_edges) > 0){
edges <- edges[-c(rm_edges), ]
}
}
# main
if(!is.null(main)){
if(is.list(main)){
if(any(!names(main)%in%c("text", "style"))){
stop("Invalid 'main' argument")
}
if(!"text"%in%names(main)){
stop("Needed a 'text' value using a list for 'main'")
}
if(!"style"%in%names(main)){
main$style <- 'font-family:Georgia, Times New Roman, Times, serif;font-weight:bold;font-size:20px;text-align:center;'
}
}else if(!inherits(main, "character")){
stop("Invalid 'main' argument. Not a character")
}else {
main <- list(text = main,
style = 'font-family:Georgia, Times New Roman, Times, serif;font-weight:bold;font-size:20px;text-align:center;')
}
}
# submain
if(!is.null(submain)){
if(is.list(submain)){
if(any(!names(submain)%in%c("text", "style"))){
stop("Invalid 'submain' argument")
}
if(!"text"%in%names(submain)){
stop("Needed a 'text' value using a list for 'submain'")
}
if(!"style"%in%names(submain)){
submain$style <- 'font-family:Georgia, Times New Roman, Times, serif;font-size:12px;text-align:center;'
}
}else if(!inherits(submain, "character")){
stop("Invalid 'submain' argument. Not a character")
}else {
submain <- list(text = submain,
style = 'font-family:Georgia, Times New Roman, Times, serif;font-size:12px;text-align:center;')
}
}
# footer
if(!is.null(footer)){
if(is.list(footer)){
if(any(!names(footer)%in%c("text", "style"))){
stop("Invalid 'footer' argument")
}
if(!"text"%in%names(footer)){
stop("Needed a 'text' value using a list for 'footer'")
}
if(!"style"%in%names(footer)){
footer$style <- 'font-family:Georgia, Times New Roman, Times, serif;font-size:12px;text-align:center;'
}
}else if(!inherits(footer, "character")){
stop("Invalid 'footer' argument. Not a character")
}else {
footer <- list(text = footer,
style = 'font-family:Georgia, Times New Roman, Times, serif;font-size:12px;text-align:center;')
}
}
if(!is.null(dot)){
x <- list(dot = dot,
options = list(width = '100%', height = "100%", nodes = list(shape = "dot"),
manipulation = list(enabled = FALSE)),
groups = NULL, width = width, height = height,
idselection = list(enabled = FALSE),
byselection = list(enabled = FALSE), main = main,
submain = submain, footer = footer, background = background)
}else if(!is.null(gephi)){
x <- list(gephi = jsonlite::fromJSON(txt = gephi, simplifyDataFrame = FALSE),
options = list(width = '100%', height = "100%", nodes = list(shape = "dot"),
manipulation = list(enabled = FALSE)),
groups = NULL, width = width, height = height,
idselection = list(enabled = FALSE),
byselection = list(enabled = FALSE), main = main,
submain = submain, footer = footer, background = background)
}else{
# forward options using x
groups = as.character(unique(nodes$group))
if(length(groups) == 0){
groups = NULL
} else if(length(groups) == 1){
groups = list(groups)
}
x <- list(nodes = nodes, edges = edges, nodesToDataframe = nodesToDataframe,
edgesToDataframe = edgesToDataframe,
options = list(width = '100%', height = "100%", nodes = list(shape = "dot"),
manipulation = list(enabled = FALSE)),
groups = groups, width = width, height = height,
idselection = list(enabled = FALSE),
byselection = list(enabled = FALSE), main = main,
submain = submain, footer = footer, background = background)
}
# previous legend control
ctrl <- list(...)
legend <- NULL
if("legend"%in%names(ctrl)){
warning("'legend' and 'legend.width' are deprecated (visNetwork >= 0.1.2). Please now prefer use visLegend function.")
if(ctrl$legend){
legend <- list()
if("legend.width"%in%names(ctrl)){
legend$width <- ctrl$legend.width
}else{
legend$width <- 0.2
}
legend$useGroups <- TRUE
legend$position <- "left"
}
}
x$legend <- legend
# create widget
htmlwidgets::createWidget(
name = 'visNetwork',
x,
width = width,
height = height,
package = 'visNetwork'
)
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visNetwork.R
|
#' Visualize, customize and get back a \code{visNetwork} object. Need shiny package
#'
#' @param object : a \code{visNetwork} object
#' @param filter : see \link{visConfigure}
#' @param showButton : see \link{visConfigure}
#'
#' @return a \code{visNetwork} object
#'
#' @examples
#'
#' \dontrun{
#'
#' nodes <- data.frame(id = 1:3, label = paste("Node", 1:3))
#' edges <- data.frame(from = c(1,2), to = c(1,3), label = paste("Edge", 1:2))
#' network <- visNetwork(nodes, edges)
#'
#' custom_network <- visNetworkEditor(object = network)
#' custom_network
#'
#' custom_network <- visNetworkEditor(object = network, filter = "nodes,edges")
#' custom_network
#'
#' }
#'
#' @export
#'
#' @importFrom utils packageVersion
#'
#' @seealso \link{visConfigure}, \link{visTree}, \link{visNetworkEditorServer}
#'
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
#'
visNetworkEditor <- function(object, filter = NULL, showButton = NULL){
if(!requireNamespace("shiny")){
stop("visNetworkEditor require 'shiny' package")
} else {
if(packageVersion("shiny") < '1.0.0'){
stop("visNetworkEditor require 'shiny' 1.0.0 or more")
}
}
# server
server <- function(input, output, session) {
shiny::callModule(visNetworkEditorServer, id = "editor" ,
object = shiny::reactive(object),
filter = shiny::reactive(filter),
showButton = shiny::reactive(showButton))
}
ui <- shiny::fluidPage(
visNetworkEditorUI(id = "editor", quitButton = TRUE)
)
return(shiny::runApp(shiny::shinyApp(ui = ui, server = server)))
}
#' Module shiny for visualize and customize and get back a \code{visNetwork} object.
#' Using the javascript interface \link{visConfigure}.
#'
#' @param input \code{list} shiny input
#' @param output \code{list}, shiny output
#' @param session \code{list}, shiny session
#' @param id \code{character} id of module, linked to \link{visNetworkEditorUI}
#' @param object a \code{visNetwork} object. Must be a reactive.
#' @param filter : see \link{visConfigure}. Must be a reactive.
#' @param showButton : see \link{visConfigure}. Must be a reactive.
#' @param quitButton : logical. Add a button for quit shiny and get back network in R ?
#' @param height : height of the configuration div. Default to "700px"
#'
#' @examples
#' \dontrun{
#'
#' nodes <- data.frame(id = 1:3, label = paste("Node", 1:3))
#' edges <- data.frame(from = c(1,2), to = c(1,3), label = paste("Edge", 1:2))
#' network <- visNetwork(nodes, edges)
#'
#' shiny::shinyApp(ui = shiny::fluidPage(
#' visNetworkEditorUI(id = "id1")),
#' server = function(input, output, session) {
#' shiny::callModule(visNetworkEditorServer, "id1", object = shiny::reactive(network))
#' })
#'
#' }
#' @name visNetworkEditor-module
#'
#' @export
#'
#' @seealso \link{visConfigure}, \link{visTree}, \link{visNetworkEditor}
#'
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
#'
#'
visNetworkEditorServer <- function(input, output, session, object,
filter = shiny::reactive(NULL), showButton = shiny::reactive(NULL)) {
ns <- session$ns
# renderNetwork
output$network <- renderVisNetwork({
object() %>%
visConfigure(enabled = TRUE, container = ns("configure"),
filter = filter(), showButton = showButton())
})
output$network_ui <- shiny::renderUI({
height <- "700px"
if(!is.null(object()$height)){
height <- object()$height
}
visNetworkOutput(ns("network"), height = height)
})
# retrieve new options on quit
shiny::observe({
if(!is.null(input$quit_btn)){
if(input$quit_btn > 0){
session$sendCustomMessage(
type='visShinyGetOptionsFromConfigurator',
message=list(id = ns("network"), input = ns(paste0("network", "_", "configurator")))
)
}
}
})
# quit and get back new network
shiny::observe({
if(!is.null(input$network_configurator)){
update_network <- object() %>%
visSetOptions(options = vis_list_clean(input$network_configurator, recursive = TRUE)) %>%
visConfigure(enabled = FALSE)
shiny::stopApp(update_network)
}
})
}
#' @rdname visNetworkEditor-module
#'
#' @export
visNetworkEditorUI <- function(id, quitButton = FALSE, height = "700px") {
ns <- shiny::NS(id)
shiny::fluidPage(
shiny::tags$head(
shiny::tags$style(HTML("input.vis-configuration.vis-config-rangeinput {visibility : hidden;}"))
),
shiny::fluidRow(
shiny::column(5,
shiny::div(id = ns("configure"),
style = paste0("overflow: auto;overflow-x: hidden; height:", height, ";")),
if(quitButton){
shiny::div(hr(), shiny::actionButton(ns("quit_btn"), "Quit and get back network in R"), align = "center")
}
),
shiny::column(7, shiny::uiOutput(ns("network_ui")))
)
)
}
vis_setmembers <- `[<-`
vis_list_clean <- function (.data, fun = is.null, recursive = FALSE)
{
if (recursive) {
.data <- lapply(.data, function(.item) {
if (is.list(.item))
vis_list_clean(.item, fun, recursive = TRUE)
else .item
})
}
vis_setmembers(.data, vapply(.data, fun, logical(1L)), NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visNetworkEditor.R
|
#' Network visualization events
#'
#' Network visualization events. For full documentation, have a look at \link{visDocumentation}.
#' Use \code{type = "once"} to set an event listener only once, and \code{type = "off"} to disable all the related events.
#'
#' @param graph : a visNetwork object
#' @param type : Character. "on" (Default) to full listener, "once" to set an event listener only once, or "off" to disable a listener.
#' @param click : Fired when the user clicks the mouse or taps on a touchscreen device.
#' @param doubleClick : Fired when the user double clicks the mouse or double taps on a touchscreen device. Since a double click is in fact 2 clicks, 2 click events are fired, followed by a double click event. If you do not want to use the click events if a double click event is fired, just check the time between click events before processing them.
#' @param oncontext : Fired when the user click on the canvas with the right mouse button. The right mouse button does not select by default. You can use the method getNodeAt to select the node if you want.
#' @param hold : Fired when the user clicks and holds the mouse or taps and holds on a touchscreen device. A click event is also fired in this case.
#' @param release : Fired after drawing on the canvas has been completed. Can be used to draw on top of the network.
#' @param select : Fired when the selection has changed by user action. This means a node or edge has been selected, added to the selection or deselected. All select events are only triggered on click and hold.
#' @param selectNode : Fired when a node has been selected by the user.
#' @param selectEdge : Fired when a edge has been selected by the user.
#' @param deselectNode : Fired when a node (or nodes) has (or have) been deselected by the user. The previous selection is the list of nodes and edges that were selected before the last user event.
#' @param deselectEdge : Fired when a edge (or edges) has (or have) been deselected by the user. The previous selection is the list of nodes and edges that were selected before the last user event.
#' @param dragStart : Fired when starting a drag.
#' @param dragging : Fired when dragging node(s) or the view.
#' @param dragEnd : Fired when the drag has finished.
#' @param controlNodeDragging : Fired when dragging control node. Control Edge is edge that is being dragged and contains ids of 'from' and 'to' nodes. If control node is not dragged over another node, 'to' field is undefined. See \link{visDocumentation}.
#' @param controlNodeDragEnd : Fired when the control node drag has finished. See \link{visDocumentation}.
#' @param hoverNode : Fired interaction:{hover:true} and the mouse hovers over a node.
#' @param blurNode : Fired interaction:{hover:true} and the mouse moved away from a node it was hovering over before.
#' @param hoverEdge : Fired interaction:{hover:true} and the mouse hovers over a edge
#' @param blurEdge : Fired interaction:{hover:true} and the mouse moved away from a edge it was hovering over before.
#' @param zoom : Fired when the user zooms in or out. The properties tell you which direction the zoom is in. The scale is a number greater than 0, which is the same that you get with network.getScale().
#' @param showPopup : Fired when the popup (tooltip) is shown.
#' @param hidePopup : Fired when the popup (tooltip) is hidden.
#' @param startStabilizing : Fired when stabilization starts. This is also the case when you drag a node and the physics simulation restarts to stabilize again. Stabilization does not neccesarily imply 'without showing'.
#' @param stabilizationProgress : Fired when a multiple of the updateInterval number of iterations is reached. This only occurs in the 'hidden' stabilization. Passes an object with properties structured as:
#' @param stabilizationIterationsDone : Fired when the 'hidden' stabilization finishes. This does not necessarily mean the network is stabilized; it could also mean that the amount of iterations defined in the options has been reached.
#' @param stabilized : Fired when the network has stabilized or when the stopSimulation() has been called. The amount of iterations it took could be used to tweak the maximum amount of iterations needed to stabilize the network.
#' @param resize : Fired when the size of the canvas has been resized, either by a redraw call when the container div has changed in size, a setSize() call with new values or a setOptions() with new width and/or height values.
#' @param initRedraw : Fired before the redrawing begins. The simulation step has completed at this point. Can be used to move custom elements before starting drawing the new frame.
#' @param beforeDrawing : Fired after the canvas has been cleared, scaled and translated to the viewing position but before all edges and nodes are drawn. Can be used to draw behind the network.
#' @param afterDrawing : Fired after drawing on the canvas has been completed. Can be used to draw on top of the network.
#' @param animationFinished : Fired when an animation is finished.
#' @param configChange : Fired when a user changes any option in the configurator. The options object can be used with the setOptions method or stringified using JSON.stringify(). You do not have to manually put the options into the network: this is done automatically. You can use the event to store user options in the database.
#'
#' @examples
#'
#' nodes <- data.frame(id = 1:3)
#' edges <- data.frame(from = c(1,2), to = c(1,3))
#'
#' visNetwork(nodes, edges) %>%
#' visEvents(select = "function(properties) {
#' alert('selected nodes: ' + properties.nodes);}",
#' dragEnd = "function(properties) {
#' alert('finish to drag');}")
#'
#' # set one
#' visNetwork(nodes, edges) %>%
#' visEvents(type = "once", select = "function() {
#' alert('first selection');}") %>%
#' visEvents(select = "function(properties) {
#' alert('selected nodes: ' + properties.nodes);}",
#' dragEnd = "function(properties) {
#' alert('finish to drag');}")
#'
#' # use this to get the network
#' visNetwork(nodes, edges) %>%
#' visEvents(type = "once", startStabilizing = "function() {
#' this.moveTo({scale:0.1})}") %>%
#' visPhysics(stabilization = FALSE)
#'
#' # shift+click, .....
#' visNetwork(nodes, edges) %>%
#' visEvents(click = "function(e) {
#' if(e.event.srcEvent.shiftKey){
#' alert('shift+click event')
#' } else if(e.event.srcEvent.ctrlKey){
#' alert('ctrl+click event')
#' }else if(e.event.srcEvent.altKey){
#' alert('alt+click event')
#' } else {
#' alert('click event')
#' }
#' }")
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @export
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visEvents <- function(graph,
type = "on",
click = NULL,
doubleClick = NULL,
oncontext = NULL,
hold = NULL,
release = NULL,
select = NULL,
selectNode = NULL,
selectEdge = NULL,
deselectNode = NULL,
deselectEdge = NULL,
dragStart = NULL,
dragging = NULL,
dragEnd = NULL,
controlNodeDragging = NULL,
controlNodeDragEnd = NULL,
hoverNode = NULL,
blurNode = NULL,
hoverEdge = NULL,
blurEdge = NULL,
zoom = NULL,
showPopup = NULL,
hidePopup = NULL,
startStabilizing = NULL,
stabilizationProgress = NULL,
stabilizationIterationsDone = NULL,
stabilized = NULL,
resize = NULL,
initRedraw = NULL,
beforeDrawing = NULL,
afterDrawing = NULL,
animationFinished = NULL,
configChange = NULL){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
stopifnot(type %in% c("on", "once", "off"))
events <- list()
events$click <- click
events$doubleClick <- doubleClick
events$oncontext <- oncontext
events$hold <- hold
events$release <- release
events$select <- select
events$selectNode <- selectNode
events$selectEdge <- selectEdge
events$deselectNode <- deselectNode
events$deselectEdge <- deselectEdge
events$dragStart <- dragStart
events$dragging <- dragging
events$dragEnd <- dragEnd
events$controlNodeDragging <- controlNodeDragging
events$controlNodeDragEnd <- controlNodeDragEnd
events$hoverNode <- hoverNode
events$blurNode <- blurNode
events$hoverEdge <- hoverEdge
events$blurEdge <- blurEdge
events$zoom <- zoom
events$showPopup <- showPopup
events$hidePopup <- hidePopup
events$startStabilizing <- startStabilizing
events$stabilizationProgress <- stabilizationProgress
events$stabilizationIterationsDone <- stabilizationIterationsDone
events$stabilized <- stabilized
events$resize <- resize
events$initRedraw <- initRedraw
events$beforeDrawing <- beforeDrawing
events$afterDrawing <- afterDrawing
events$animationFinished <- animationFinished
events$configChange <- configChange
if(any(class(graph) %in% "visNetwork_Proxy")){
data <- list(id = graph$id, type = type, events = events)
graph$session$sendCustomMessage("visShinyEvents",data)
}else{
events <- lapply(events, function(x) htmlwidgets::JS(x))
if(type %in% "on"){
graph$x$events <- mergeLists(graph$x$events, events)
} else if (type %in% "once"){
graph$x$OnceEvents <- mergeLists(graph$x$OnceEvents, events)
} else if (type %in% "off"){
graph$x$ResetEvents <- mergeLists(graph$x$ResetEvents, events)
}
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visNetworkEvents.R
|
#' Shiny bindings for visNetwork
#'
#' Output and render functions for using visNetwork within Shiny
#' applications and interactive Rmd documents. With \code{visNetworkProxy},
#' you can update your network without redraw in shiny.
#'
#' @param outputId : output variable to read from
#' @param width,height Must be a valid CSS unit (like \code{"100\%"},
#' \code{"400px"}, \code{"auto"}) or a number, which will be coerced to a
#' string and have \code{"px"} appended.
#' @param expr An expression that generates a visNetwork
#' @param env The environment in which to evaluate \code{expr}.
#' @param quoted Is \code{expr} a quoted expression (with \code{quote()})? This
#' is useful if you want to save an expression in a variable.
#' @param shinyId single-element character vector indicating the shiny output ID of the
#' network to modify
#' @param session the Shiny session object to which the map belongs; usually the
#' default value will suffice
#'
#' @name visNetwork-shiny
#'
#' @details
#'
#' With \code{visNetworkProxy}, you can update your network and use various methods :
#' \itemize{
#' \item{"all 'visNetwork' functions"}{ : \code{\link{visOptions}}, \code{\link{visNodes}}, \code{\link{visEdges}}, \code{\link{visPhysics}}, \code{\link{visEvents}}, ...}
#' \item{\code{\link{visFocus}}}{ : Focus to one or more nodes}
#' \item{\code{\link{visFit}}}{ : Set view on a set of nodes}
#' \item{\code{\link{visUpdateNodes}}}{ : Update and add nodes}
#' \item{\code{\link{visUpdateEdges}}}{ : Update and add edges}
#' \item{\code{\link{visRemoveNodes}}}{ : Remove nodes}
#' \item{\code{\link{visRemoveEdges}}}{ : Remove edges}
#' \item{\code{\link{visSelectNodes}}}{ :Select nodes}
#' \item{\code{\link{visSelectEdges}}}{ : Select edges}
#' \item{\code{\link{visGetNodes}}}{ : Get nodes dataset}
#' \item{\code{\link{visGetEdges}}}{ : Get edges dataset}
#' \item{\code{\link{visSetSelection}}}{ : Select edges/nodes}
#' \item{\code{\link{visNearestNodes}}}{ : Get nearest nodes}
#' \item{\code{\link{visCollapse}}}{ : Collapse nodes}
#' \item{\code{\link{visUncollapse}}}{ : Uncollpase nodes}
#' \item{\code{\link{visSetTitle}}}{ : Set and update main, submain, footer}
#' \item{and also...}{ : \code{\link{visGetSelectedEdges}}, \code{\link{visGetSelectedNodes}}, \code{\link{visGetSelection}},
#' \code{\link{visGetConnectedEdges}}, \code{\link{visGetConnectedNodes}}, \code{\link{visRedraw}}, \code{\link{visStabilize}},
#' \code{\link{visSetData}}, \code{\link{visGetPositions}}, \code{\link{visMoveNode}}, \code{\link{visUnselectAll}},
#' \code{\link{visGetScale}}, \code{\link{visGetBoundingBox}}, \code{\link{visGetViewPosition}},\code{\link{visSetOptions}}}
#'}
#'
#' @examples
#'
#'\dontrun{
#'
#' # have a look to :
#' shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#' @export
#'
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
#'
visNetworkOutput <- function(outputId, width = '100%', height = '400px'){
shinyWidgetOutput(outputId, 'visNetwork', width, height, package = 'visNetwork')
}
#' @rdname visNetwork-shiny
#' @export
renderVisNetwork <- function(expr, env = parent.frame(), quoted = FALSE) {
if (!quoted) { expr <- substitute(expr) } # force quoted
shinyRenderWidget(expr, visNetworkOutput, env, quoted = TRUE)
}
#' @name visNetwork-shiny
#'
#' @export
visNetworkProxy <- function(shinyId, session = shiny::getDefaultReactiveDomain()){
if (is.null(session)) {
stop("visNetworkProxy must be called from the server function of a Shiny app")
}
object <- list(id = shinyId, session = session)
class(object) <- "visNetwork_Proxy"
object
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visNetworkProxy.R
|
#' Network visualization nodes options
#'
#' Network visualization nodes options. For full documentation, have a look at \link{visDocumentation}.
#'
#' @param graph : a visNetwork object
#' @param id : String. Default to undefined. The id of the node. The id is mandatory for nodes and they have to be unique. This should obviously be set per node, not globally.
#' @param shape : String. Default to 'ellipse'. The shape defines what the node looks like. There are two types of nodes. One type has the label inside of it and the other type has the label underneath it. The types with the label inside of it are: ellipse, circle, database, box, text. The ones with the label outside of it are: image, circularImage, diamond, dot, star, triangle, triangleDown, hexagon, square and icon.
#' @param size : Number. Default to 25. The size is used to determine the size of node shapes that do not have the label inside of them. These shapes are: image, circularImage, diamond, dot, star, triangle, triangleDown, hexagon, square and icon
#' @param title : String or Element. Default to undefined. Title to be displayed when the user hovers over the node. The title can be an HTML element or a string containing plain text or HTML.
#' @param value : Number. Default to undefined. When a value is set, the nodes will be scaled using the options in the scaling object defined above.
#' @param x : Number. Default to undefined. This gives a node an initial x position. When using the hierarchical layout, either the x or y position is set by the layout engine depending on the type of view. The other value remains untouched. When using stabilization, the stabilized position may be different from the initial one. To lock the node to that position use the physics or fixed options.
#' @param y : Number. Default to undefined. This gives a node an initial y position. When using the hierarchical layout, either the x or y position is set by the layout engine depending on the type of view. The other value remains untouched. When using stabilization, the stabilized position may be different from the initial one. To lock the node to that position use the physics or fixed options.
#' @param label : String. Default to undefined. The label is the piece of text shown in or under the node, depending on the shape.
#' @param level : Number. Default to undefined. When using the hierarchical layout, the level determines where the node is going to be positioned.
#' @param group : String. Default to undefined. When not undefined, the node will belong to the defined group. Styling information of that group will apply to this node. Node specific styling overrides group styling.
#' @param hidden : Boolean. Default to false. When true, the node will not be shown. It will still be part of the physics simulation though!
#' @param image : List or String. Default to undefined. When the shape is set to image or circularImage, this option should be the URL to an image. If the image cannot be found, the brokenImage option can be used.
#' \itemize{
#' \item{"unselected"}{ : String. Unselected (default) image URL.}
#' \item{"selected"}{ : String. Selected image URL.}
#' }
#' @param mass : Number. Default to 1. The barnesHut physics model (which is enabled by default) is based on an inverted gravity model. By increasing the mass of a node, you increase it's repulsion. Values lower than 1 are not recommended.
#' @param physics : Boolean. Default to true. When false, the node is not part of the physics simulation. It will not move except for from manual dragging.
#' @param borderWidth : Number. Default to 1. The width of the border of the node when it is not selected, automatically limited by the width of the node.
#' @param borderWidthSelected : Number. Default to 2. The width of the border of the node when it is selected. If left at undefined, double the borderWidth will be used.
#' @param brokenImage : String. Undefined. When the shape is set to image or circularImage, this option can be an URL to a backup image in case the URL supplied in the image option cannot be resolved
#' @param labelHighlightBold : Boolean. Default to true. Determines whether or not the label becomes bold when the node is selected.
#' @param color : String | named list. Color for the node. Can be 'rgba(120,32,14,1)', '#D2E5FF' (hexa notation on 7 char without transparency) or 'red'. Can be just one color, or a list with several elements :
#' \itemize{
#' \item{"background"}{ : String. Default to '#D2E5FF'. Background color for the node.}
#' \item{"border"}{ : String. Default to '#2B7CE9'. Border color for the node.}
#' \item{"highlight"}{ : String | named list, Color of the node when selected.
#' \itemize{
#' \item{"background"}{ : String. Default to '#D2E5FF'. Background color for the node when selected.}
#' \item{"border"}{ : String. Default to '#2B7CE9'. Border color for the node when selected.}
#' }
#' }
#' \item{"hover"}{ : named list, when the hover option is enabled
#' \itemize{
#' \item{"background"}{ : String. Default to '#D2E5FF'. Background color of the node when the node is hovered over and the hover option is enabled.}
#' \item{"border"}{ : String. Default to '#2B7CE9'. Border color of the node when the node is hovered over and the hover option is enabled.}
#' }
#' }
#'}
#' @param opacity : Number. Overall opacity of a node (overrides any opacity on border, background, image, and shadow)
#' @param fixed : Boolean | named list. Default to false. When true, the node will not move but IS part of the physics simulation. When defined as an list, movement in either X or Y direction can be disabled.
#' \itemize{
#' \item{"x"}{ : Boolean. When true, the node will not move in the X direction.}
#' \item{"y"}{ : Boolean. When true, the node will not move in the Y direction.}
#'}
#'
#' @param font : Named list or String. This object defines the details of the label. A shorthand is also supported in the form 'size face color' for example: '14px arial red'
#' \itemize{
#' \item{"color"}{ : String. Default to '#343434'. Color of the label text.}
#' \item{"size"}{ : Number. Default to 14. Size of the label text.}
#' \item{"face"}{ : String. Default to 'arial. Font face (or font family) of the label text.}
#' \item{"background"}{ : String. Default to undefined. When not undefined but a color string, a background rectangle will be drawn behind the label in the supplied color.}
#' \item{"strokeWidth"}{ : Number. Default to 0. As an alternative to the background rectangle, a stroke can be drawn around the text. When a value higher than 0 is supplied, the stroke will be drawn.}
#' \item{"strokeColor"}{ : String. Default to '#ffffff'. This is the color of the stroke assuming the value for stroke is higher than 0.}
#' \item{"align"}{ : String. Default to 'center'. This can be set to 'left' to make the label left-aligned}
#' \item{"vadjust, multi, bold, ital, boldital, mono"}{See \link{visDocumentation}}
#'}
#'
#' @param icon : Named list. These options are only used when the shape is set to 'icon'. See \link{addFontAwesome}, \link{addIonicons}
#' \itemize{
#' \item{"face"}{ : String. Default to 'FontAwesome'. These options are only used when the shape is set to icon. The possible options for the face are: 'FontAwesome', "'Font Awesome 5 Free'", and 'Ionicons'.}
#' \item{"code"}{ : String. Default to undefined. This is the code of the icon, for example '\\uf007'.}
#' \item{"size"}{ : Number. Default to 50. The size of the icon.}
#' \item{"color"}{ : String. Default to '#2B7CE9'. The color of the icon.}
#' \item{"weight"}{ : Number or String. Default to undefined. This allows for weight to be forced regardless of selection status. For example Font Awesome 5 doesn't work properly unless weight is forced to 'bold' or 700 (This is done automatically in visNetwork). If this option is set then selection is indicated by bigger size instead of bold font face. }
#'}
#'
#' @param shadow : Boolean | named list. Default to false. When true, the node casts a shadow using the default settings. This can be further refined by supplying a list
#' \itemize{
#' \item{"enabled"}{ : Boolean. Default to false. Toggle the casting of shadows. If this option is not defined, it is set to true if any of the properties in this object are defined.}
#' \item{"color"}{ : String. Default to 'rgba(0,0,0,0.5)'. The color of the shadow as a string. Supported formats are 'rgb(255,255,255)', 'rgba(255,255,255,1)' and '#FFFFFF'.}
#' \item{"size"}{ : Number. Default to 10. The blur size of the shadow.}
#' \item{"x"}{ : Number. Default to 5. The x offset.}
#' \item{"y"}{ : Number. Default to 5. The y offset.}
#'}
#'
#' @param scaling : Named list. If the value option is specified, the size of the nodes will be scaled according to the properties in this object.
#' \itemize{
#' \item{"min"}{ : Number. Default to 10. If nodes have a value, their sizes are determined by the value, the scaling function and the min max values.}
#' \item{"max"}{ : Number. Default to 30. This is the maximum allowed size when the nodes are scaled using the value option.}
#' \item{"label"}{ : Named list or Boolean. Default to Named list. This can be false if the label is not allowed to scale with the node. If true it will scale using default settigns. For further customization, you can supply an object.
#' \itemize{
#' \item{"enabled"}{ : Boolean. Default to false. Toggle the scaling of the label on or off. If this option is not defined, it is set to true if any of the properties in this object are defined.}
#' \item{"min"}{ : Number. Default to 14. The minimum font-size used for labels when scaling.}
#' \item{"max"}{ : Number. Default to 30. The maximum font-size used for labels when scaling.}
#' \item{"maxVisible"}{ : Number. Default to 30. When zooming in, the font is drawn larger as well. You can limit the perceived font size using this option. If set to 30, the font will never look larger than size 30 zoomed at 100\%.}
#' \item{"drawThreshold"}{ : Number. Default to 5. When zooming out, the font will be drawn smaller. This defines a lower limit for when the font is drawn. When using font scaling, you can use this together with the maxVisible to first show labels of important nodes when zoomed out and only show the rest when zooming in.}
#' }
#' }
#' \item{"customScalingFunction"}{ : Function. If nodes have value fields, this function determines how the size of the nodes are scaled based on their values.}
#'}
#'
#' @param shapeProperties : See \link{visDocumentation}
#'
#' @param heightConstraint : See \link{visDocumentation}
#' @param widthConstraint : See \link{visDocumentation}
#' @param margin : See \link{visDocumentation}
#' @param chosen : See \link{visDocumentation}
#' @param imagePadding : See \link{visDocumentation}
#' @param ctxRenderer : See \link{visDocumentation}
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'
#' \dontrun{
#' nodes <- data.frame(id = 1:3)
#' edges <- data.frame(from = c(1,2), to = c(1,3))
#'
#' visNetwork(nodes, edges) %>%
#' visNodes(shape = "square", title = "I'm a node", borderWidth = 3)
#'
#' visNetwork(nodes, edges) %>%
#' visNodes(color = list(hover = "green")) %>%
#' visInteraction(hover = TRUE)
#'
#'
#' visNetwork(nodes, edges) %>% visNodes(color = "red")
#'
#' visNetwork(nodes, edges) %>%
#' visNodes(color = list(background = "red", border = "blue",
#' highlight = "yellow"))
#'
#' visNetwork(nodes, edges) %>% visNodes(shadow = TRUE)
#'
#' visNetwork(nodes, edges) %>% visNodes(shadow = list(enabled = TRUE, size = 50))
#'
#' }
#'
#' @export
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visNodes <- function(graph,
id = NULL,
shape = NULL,
size = NULL,
title = NULL,
value = NULL,
x = NULL,
y = NULL,
label = NULL,
level = NULL,
group = NULL,
hidden = NULL,
image = NULL,
mass = NULL,
physics = NULL,
borderWidth = NULL,
borderWidthSelected = NULL,
brokenImage = NULL,
labelHighlightBold = NULL,
color = NULL,
opacity = NULL,
fixed = NULL,
font = NULL,
icon = NULL,
shadow = NULL,
scaling = NULL,
shapeProperties = NULL,
heightConstraint = NULL,
widthConstraint = NULL,
margin = NULL,
chosen = NULL,
imagePadding = NULL,
ctxRenderer = NULL){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
nodes <- list()
nodes$id <- id
nodes$shape <- shape
nodes$size <- size
nodes$title <- title
nodes$value <- value
nodes$x <- x
nodes$y <- y
nodes$label <- label
nodes$level <- level
nodes$group <- group
nodes$hidden <- hidden
nodes$image <- image
nodes$imagePadding <- imagePadding
nodes$mass <- mass
nodes$physics <- physics
nodes$borderWidth <- borderWidth
nodes$borderWidthSelected <- borderWidthSelected
nodes$brokenImage <- brokenImage
nodes$labelHighlightBold <- labelHighlightBold
nodes$color <- color
nodes$opacity <- opacity
nodes$fixed <- fixed
nodes$font <- font
nodes$icon <- icon
nodes$shadow <- shadow
nodes$shapeProperties <- shapeProperties
nodes$margin <- margin
nodes$chosen <- chosen
nodes$widthConstraint <- widthConstraint
nodes$heightConstraint <- heightConstraint
if(!is.null(scaling)){
if("customScalingFunction"%in%names(scaling)){
scaling$customScalingFunction <- JS(scaling$customScalingFunction)
}
}
nodes$scaling <- scaling
nodes$ctxRenderer <- ctxRenderer
if(any(class(graph) %in% "visNetwork_Proxy")){
options <- list(nodes = nodes)
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyOptions",data)
}else{
graph$x$options$nodes <- mergeLists(graph$x$options$nodes, nodes)
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visNodes.R
|
#' Network visualization general options
#'
#' Network visualization general options. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a visNetwork object
#'@param width : String. Default to "100\%". The width of the network in pixels or as a percentage.
#'@param height : String. Default to "100\%". The height of the network in pixels or as a percentage.
#'@param highlightNearest : Custom Option. Just a Boolean, or a named list. Default to false. Highlight nearest when clicking a node ? Not available for DOT and Gephi.
#'\itemize{
#' \item{"enabled"}{ : Boolean. Default to false. Activated or not ?.}
#' \item{"degree"}{ : Optional. Integer. Degree of depth of nodes to be colored. Default to 1. Set high number to have the entire sub-network. In case of "hierarchical" algorithm, you can also pass a list(from = 1, to = 1) to control degree in both direction}
#' \item{"hover"}{ : Optional. Boolean. Enable highlightNearest alos hovering a node ? Default to FALSE}
#' \item{"algorithm"}{ : Optional. String. highlightNearest algorithm. "all" highlight all nodes, without taking direction information. "hierarchical" look only at inputs/outputs nodes.}
#' \item{"hideColor"}{ : Optional. String. Color for hidden nodes/edges. Use a rgba definition. Default to rgba(200,200,200,0.5)}
#' \item{"labelOnly"}{ : Optional. Boolean. Keep just label for nodes on degree + 1 ? Default to TRUE}
#'}
#'@param nodesIdSelection : Custom Option. Just a Boolean, or a named list. Default to false. Add an id node selection creating an HTML select element. This options use click event. Not available for DOT and Gephi.
#'\itemize{
#' \item{"enabled"}{ : Boolean. Default to false. Activated or not ?.}
#' \item{"values}{ : Optional. Vector of possible values (node's id), and so order is preserve. Default to all id in nodes data.frame.}
#' \item{"selected"}{ : Optional. Integer/Character. Initial id selection. Default to NULL}
#' \item{"style"}{ : Optional. Character. HTML style of list. Default to 'width: 150px; height: 26px'.}
#' \item{"useLabels"}{ : Optional. Boolean. Use labels instead of id ? Default to TRUE.}
#' \item{"main"}{ : Optional. Default to "Select by id"}
#'}
#'@param selectedBy : Custom option. Character or a named list. Add a multiple selection based on column of node data.frame creating an HTML select element. Not available for DOT and Gephi.
#'\itemize{
#' \item{"variable"}{ : Character. Column name of selection variable.}
#' \item{"values}{ : Optional. Vector of possible values. Default to all values in nodes data.frame.}
#' \item{"selected"}{ : Optional. Integer/Character. Initial selection. Default to NULL}
#' \item{"style"}{ : Optional. Character. HTML style of list. Default to 'width: 150px; height: 26px'.}
#' \item{"multiple"}{ : Optional. Boolean. Default to FALSE. If TRUE, you can affect multiple groups per nodes using a comma ("gr1,gr2")}
#' \item{"hideColor"}{ : Optional. String. Color for hidden nodes/edges. Use a rgba definition. Default to rgba(200,200,200,0.5)}
#' \item{"main"}{ : Optional. Default to "Select by variable"}
#' \item{"sort"}{ : Optional. If values is NULL, sort all possible values ?. Default to TRUE}
#' \item{"highlight"}{ : Optional. Boolean. Run highlightNearest if defined on each selected node ? Default to FALSE}
#'}
#'@param collapse : Custom option. Just a Boolean, or a named list. Collapse / Uncollapse nodes using double-click. In dev.
#'\itemize{
#' \item{"enabled"}{ : Boolean. Default to false. Activated or not ?}
#' \item{"fit"}{ : Optional. Boolean. Default to FALSE. Call fit method after collapse/uncollapse event ?}
#' \item{"resetHighlight"}{ : Optional. Boolean. Default to TRUE to reset highlighted nodes after collapse/uncollapse event.}
#' \item{"clusterOptions"}{ : Optional. List. Default to NULL. A list of all options you want to pass to cluster collapsed node}
#' \item{"keepCoord"}{ : Optional. Boolean. Default to TRUE to keep nodes coordinates on collapse}
#' \item{"labelSuffix"}{ : Optional. Character. Use node label + suffix or just suffix. Default to '(cluster)'}
#'}
#'@param autoResize : Boolean. Default to true. If true, the Network will automatically detect when its container is resized, and redraw itself accordingly. If false, the Network can be forced to repaint after its container has been resized using the function redraw() and setSize().
#'@param clickToUse : Boolean. Default to false. When a Network is configured to be clickToUse, it will react to mouse, touch, and keyboard events only when active. When active, a blue shadow border is displayed around the Network. The Network is set active by clicking on it, and is changed to inactive again by clicking outside the Network or by pressing the ESC key.
#'@param manipulation : Just a Boolean or a list. See \link{visDocumentation}. You can also choose the columns to edit :
#'\itemize{
#' \item{"editEdgeCols"}{ : Optional. Default to NULL, and so you can just move edge. If set, you can't move edge but just edit.}
#' \item{"editNodeCols"}{ : Optional. Default to c("id", "label"). See examples.}
#' \item{"addNodeCols"}{ : Optional. Default to c("id", "label"). See examples.}
#'}
#'@examples
#'
#'\dontrun{
#' nodes <- data.frame(id = 1:15, label = paste("Label", 1:15),
#' group = sample(LETTERS[1:3], 15, replace = TRUE))
#'
#' edges <- data.frame(from = trunc(runif(15)*(15-1))+1,
#' to = trunc(runif(15)*(15-1))+1)
#'
#' ###################
#' # highlight nearest
#' ###################
#'
#' visNetwork(nodes, edges) %>% visOptions(highlightNearest = TRUE)
#' visNetwork(nodes, edges) %>% visOptions(highlightNearest = list(enabled = TRUE, degree = 2))
#'
#' # also when hover a node ?
#' visNetwork(nodes, edges) %>% visOptions(highlightNearest = list(enabled = TRUE, hover = TRUE))
#'
#' # don't show nodes/edges
#' visNetwork(nodes, edges) %>% visOptions(highlightNearest = list(enabled = TRUE,
#' hover = TRUE, hideColor = 'rgba(200,200,200,0)'))
#'
#' # Using hierarchical information
#' nodes = data.frame(id = 1:6, level = c(1, 2, 3, 3, 4, 2))
#' edges = data.frame(from = c(1, 2, 2, 4, 6), to = c(2, 3, 4, 5, 4))
#'
#' visNetwork(nodes, edges) %>% visHierarchicalLayout() %>% visEdges(arrows = "to") %>%
#' visOptions(highlightNearest = list(enabled = TRUE, algorithm = "hierarchical"))
#'
#' visNetwork(nodes, edges) %>% visHierarchicalLayout() %>% visEdges(arrows = "to") %>%
#' visOptions(highlightNearest = list(enabled = TRUE, algorithm = "hierarchical",
#' degree = list(from = 0, to = 2)))
#'
#' ##########################
#' # nodesIdSelection
#' ##########################
#'
#' visNetwork(nodes, edges) %>%
#' visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)
#'
#' # add a default selected node ?
#' visNetwork(nodes, edges) %>%
#' visOptions(highlightNearest = TRUE,
#' nodesIdSelection = list(enabled = TRUE, selected = "1"))
#'
#' # subset on id values & don't use labels ?
#' visNetwork(nodes, edges) %>%
#' visOptions(highlightNearest = TRUE,
#' nodesIdSelection = list(enabled = TRUE,
#' selected = "2", values = c(2:10), useLabels = FALSE))
#'
#' # some style
#' visNetwork(nodes, edges) %>%
#' visOptions(highlightNearest = TRUE,
#' nodesIdSelection = list(enabled = TRUE, style = 'width: 200px; height: 26px;
#' background: #f8f8f8;
#' color: darkblue;
#' border:none;
#' outline:none;'))
#'
#' ##########################
#' # collapse
#' ##########################
#'
#' nodes <- data.frame(id = 1:15, label = paste("Label", 1:15),
#' group = sample(LETTERS[1:3], 15, replace = TRUE))
#'
#' edges <- data.frame(from = trunc(runif(15)*(15-1))+1,
#' to = trunc(runif(15)*(15-1))+1)
#'
#' # keeping all parent node attributes
#' visNetwork(nodes, edges) %>% visEdges(arrows = "to") %>%
#' visOptions(collapse = TRUE)
#'
#' # setting some properties
#' visNetwork(nodes, edges) %>% visEdges(arrows = "to") %>%
#' visOptions(collapse = list(enabled = TRUE, clusterOptions = list(shape = "square")))
#'
#' # enable / disable open cluster (proxy only) :
#' # visEvents(type = "off", doubleClick = "networkOpenCluster")
#' # visEvents(type = "on", doubleClick = "networkOpenCluster")
#'
#' ##########################
#' # selectedBy
#' ##########################
#' nodes <- data.frame(id = 1:15, label = paste("Label", 1:15),
#' group = sample(LETTERS[1:3], 15, replace = TRUE))
#'
#' edges <- data.frame(from = trunc(runif(15)*(15-1))+1,
#' to = trunc(runif(15)*(15-1))+1)
#'
#' visNetwork(nodes, edges) %>%
#' visOptions(selectedBy = "group")
#'
#' # add a default value ?
#' visNetwork(nodes, edges) %>%
#' visOptions(selectedBy = list(variable = "group", selected = "A"))
#'
#' # subset on values ?
#' visNetwork(nodes, edges) %>%
#' visOptions(selectedBy = list(variable = "group",
#' selected = "C",
#' values = c("A", "C")))
#'
#' # highlight also
#' visNetwork(nodes, edges) %>%
#' visOptions(selectedBy = list(variable = "group",
#' highlight = TRUE), highlightNearest = TRUE)
#'
#' # add some style
#' visNetwork(nodes, edges) %>%
#' visOptions(selectedBy = list(variable = "group", style = 'width: 200px; height: 26px;
#' background: #f8f8f8;
#' color: darkblue;
#' border:none;
#' outline:none;'))
#'
#' # can also be on new column
#' nodes$sample <- sample(c("sample 1", "sample 2"), nrow(nodes), replace = TRUE)
#' visNetwork(nodes, edges) %>%
#' visOptions(selectedBy = "sample")
#'
#' # and with multiple groups ?
#' nodes$group <- sample(c("group 1", "group 2", "group 1, group 2, group 3"),
#' nrow(nodes), replace = TRUE)
#'
#' visNetwork(nodes, edges) %>%
#' visOptions(selectedBy = list(variable = "group", multiple = TRUE))
#'
#' ##########################
#' # manipulation
#' ##########################
#'
#'visNetwork(nodes, edges) %>%
#' visOptions(manipulation = TRUE)
#'
#'visNetwork(nodes, edges) %>%
#' visOptions(manipulation = list(enabled = TRUE, addNode = FALSE, addEdge = FALSE))
#'
#'visNetwork(nodes, edges) %>%
#' visOptions(manipulation = list(enabled = TRUE, deleteNode = FALSE, deleteEdge = FALSE))
#'
#'visNetwork(nodes, edges) %>%
#' visOptions(manipulation = list(enabled = TRUE, editNode = FALSE, editEdge = FALSE))
#'
#' # choose columns to edit
#' visNetwork(nodes, edges) %>%
#' visOptions(manipulation = list(enabled = TRUE,
#' editEdgeCols = c("label"),
#' editNodeCols = c("id", "label", "title", "size"),
#' addNodeCols = c("label", "group")))
#'
#' # choose columns to edit + input html type (text, number, ...)
#' # https://www.w3schools.com/tags/att_input_type.asp
#' visNetwork(nodes, edges) %>%
#' visOptions(manipulation = list(enabled = TRUE,
#' editEdgeCols = c("label"),
#' editNodeCols = list(
#' "text" = c("id", "label", "title"),
#' "number" = c("size")
#' ),
#' addNodeCols = c("label", "group")))
#'visNetwork(nodes, edges) %>%
#' visOptions(manipulation = list(enabled = TRUE,
#' editEdge = htmlwidgets::JS("function(data, callback) {
#' callback(data);
#' console.info('edit edge')
#' }")
#' )
#' )
#' ##########################
#' # collapse
#' ##########################
#' visNetwork(nodes, edges) %>%
#' visEdges(arrows = "to") %>%
#' visOptions(collapse = list(enabled = TRUE,
#' clusterOptions = list(shape = "square")))
#'}
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visOptions <- function(graph,
width = NULL,
height = NULL,
highlightNearest = FALSE,
nodesIdSelection = FALSE,
selectedBy = NULL,
collapse = FALSE,
autoResize = NULL,
clickToUse = NULL,
manipulation = NULL){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
options <- list()
options$autoResize <- autoResize
options$clickToUse <- clickToUse
if(is.null(manipulation)){
options$manipulation <- list(enabled = FALSE)
}else{
graph$x$opts_manipulation$datacss <- paste(readLines(system.file("htmlwidgets/lib/css/dataManipulation.css", package = "visNetwork"), warn = FALSE), collapse = "\n")
if(is.logical(manipulation)){
options$manipulation <- list(enabled = manipulation)
} else if(is.list(manipulation)){
options$manipulation <- manipulation
} else {
stop("Invalid 'manipulation' argument. logical or list")
}
if(!"addNodeCols" %in% names(manipulation)){
graph$x$opts_manipulation$addNodeCols <- c("id", "label")
addNodeCols_html_input_type <- rep("text", 2)
} else {
if(is.list(manipulation$addNodeCols)){
graph$x$opts_manipulation$addNodeCols <- unname(do.call("c", manipulation$addNodeCols))
addNodeCols_html_input_type <- rep(names(manipulation$addNodeCols), sapply(manipulation$addNodeCols, length))
} else if(is.vector(manipulation$addNodeCols)){
graph$x$opts_manipulation$addNodeCols <- manipulation$addNodeCols
addNodeCols_html_input_type <- rep("text", length(manipulation$addNodeCols))
}
options$manipulation$addNodeCols <- NULL
}
if(!"editNodeCols" %in% names(manipulation)){
graph$x$opts_manipulation$editNodeCols <- c("id", "label")
editNodeCols_html_input_type <- rep("text", 2)
} else {
if(is.list(manipulation$editNodeCols)){
graph$x$opts_manipulation$editNodeCols <- unname(do.call("c", manipulation$editNodeCols))
editNodeCols_html_input_type <- rep(names(manipulation$editNodeCols), sapply(manipulation$editNodeCols, length))
} else if(is.vector(manipulation$editNodeCols)){
graph$x$opts_manipulation$editNodeCols <- manipulation$editNodeCols
editNodeCols_html_input_type <- rep("text", length(manipulation$editNodeCols))
}
options$manipulation$editNodeCols <- NULL
}
if("editEdgeCols" %in% names(manipulation) && !is.null(manipulation$editEdgeCols) && length(manipulation$editEdgeCols) > 0){
if(is.list(manipulation$editEdgeCols)){
graph$x$opts_manipulation$editEdgeCols <- unname(do.call("c", manipulation$editEdgeCols))
editEdgeCols_html_input_type <- rep(names(manipulation$editEdgeCols), sapply(manipulation$editEdgeCols, length))
} else if(is.vector(manipulation$editEdgeCols)){
graph$x$opts_manipulation$editEdgeCols <- manipulation$editEdgeCols
editEdgeCols_html_input_type <- rep("text", length(manipulation$editEdgeCols))
}
options$manipulation$editEdgeCols <- NULL
}
if(length(graph$x$opts_manipulation$addNodeCols) == 1){
graph$x$opts_manipulation$addNodeCols <- list(graph$x$opts_manipulation$addNodeCols)
}
if(length(graph$x$opts_manipulation$editNodeCols) == 1){
graph$x$opts_manipulation$editNodeCols <- list(graph$x$opts_manipulation$editNodeCols)
}
if(length(graph$x$opts_manipulation$editEdgeCols) == 1){
graph$x$opts_manipulation$editEdgeCols <- list(graph$x$opts_manipulation$editEdgeCols)
}
if(!is.null(graph$x$opts_manipulation$addNodeCols)){
graph$x$opts_manipulation$tab_add_node <- build_manipulation_table(
col = graph$x$opts_manipulation$addNodeCols,
type = addNodeCols_html_input_type,
id = "addnode")
}
if(!is.null(graph$x$opts_manipulation$editNodeCols)){
graph$x$opts_manipulation$tab_edit_node <- build_manipulation_table(
col = graph$x$opts_manipulation$editNodeCols,
type = editNodeCols_html_input_type,
id = "editnode")
}
if(!is.null(graph$x$opts_manipulation$editEdgeCols)){
graph$x$opts_manipulation$tab_edit_edge <- build_manipulation_table(
col = graph$x$opts_manipulation$editEdgeCols,
type = editEdgeCols_html_input_type,
id = "editedge")
}
}
options$height <- height
options$width <- width
if(!"nodes"%in%names(graph$x) && any(class(graph) %in% "visNetwork")){
highlight <- list(enabled = FALSE)
idselection <- list(enabled = FALSE)
byselection <- list(enabled = FALSE)
list_collapse <- list(enabled = FALSE, fit = FALSE, resetHighlight = TRUE,
keepCoord = TRUE, labelSuffix = "(cluster)")
}else{
#############################
# collapse
#############################
list_collapse <- list(enabled = FALSE, fit = FALSE, resetHighlight = TRUE,
clusterOptions = NULL, keepCoord = TRUE, labelSuffix = "(cluster)")
if(is.list(collapse)){
if(any(!names(collapse)%in%c("enabled", "fit", "resetHighlight", "clusterOptions", "keepCoord", "labelSuffix"))){
stop("Invalid 'collapse' argument")
}
if("enabled"%in%names(collapse)){
stopifnot(is.logical(collapse$enabled))
list_collapse$enabled <- collapse$enabled
}
if("fit"%in%names(collapse)){
stopifnot(is.logical(collapse$fit))
list_collapse$fit <- collapse$fit
}
if("resetHighlight"%in%names(collapse)){
stopifnot(is.logical(collapse$resetHighlight))
list_collapse$resetHighlight <- collapse$resetHighlight
}
if("keepCoord"%in%names(collapse)){
stopifnot(is.logical(collapse$keepCoord))
list_collapse$keepCoord <- collapse$keepCoord
}
if("labelSuffix"%in%names(collapse)){
stopifnot(is.character(collapse$labelSuffix))
list_collapse$labelSuffix <- collapse$labelSuffix
}
if("clusterOptions"%in%names(collapse)){
stopifnot(is.list(collapse$clusterOptions))
list_collapse$clusterOptions <- collapse$clusterOptions
}
} else {
stopifnot(is.logical(collapse))
list_collapse$enabled <- collapse
}
#############################
# highlightNearest
#############################
highlight <- list(enabled = FALSE, hoverNearest = FALSE, degree = 1, algorithm = "all", hideColor = 'rgba(200,200,200,0.5)', labelOnly = TRUE)
if(is.list(highlightNearest)){
if(any(!names(highlightNearest)%in%c("enabled", "degree", "hover", "algorithm", "hideColor", "labelOnly"))){
stop("Invalid 'highlightNearest' argument")
}
if("algorithm"%in%names(highlightNearest)){
stopifnot(highlightNearest$algorithm %in% c("all", "hierarchical"))
highlight$algorithm <- highlightNearest$algorithm
}
if("hideColor"%in%names(highlightNearest)){
highlight$hideColor <- highlightNearest$hideColor
}
if("degree"%in%names(highlightNearest)){
highlight$degree <- highlightNearest$degree
}
if(highlight$algorithm %in% "hierarchical"){
if(is.list(highlight$degree)){
stopifnot(all(names(highlight$degree) %in% c("from", "to")))
}else{
highlight$degree <- list(from = highlight$degree, to = highlight$degree)
}
}
if("labelOnly"%in%names(highlightNearest)){
stopifnot(is.logical(highlightNearest$labelOnly))
highlight$labelOnly <- highlightNearest$labelOnly
}
if("hover"%in%names(highlightNearest)){
stopifnot(is.logical(highlightNearest$hover))
highlight$hoverNearest <- highlightNearest$hover
}
if("enabled"%in%names(highlightNearest)){
stopifnot(is.logical(highlightNearest$enabled))
highlight$enabled <- highlightNearest$enabled
}
} else {
stopifnot(is.logical(highlightNearest))
highlight$enabled <- highlightNearest
}
if(highlight$enabled && any(class(graph) %in% "visNetwork")){
if(!"label"%in%colnames(graph$x$nodes)){
if(is.data.frame(graph$x$nodes)){
graph$x$nodes$label <- as.character(graph$x$nodes$id)
} else if(is.list(graph$x$nodes)){
ctrl <- lapply(1:length(graph$x$nodes), function(x){
graph$x$nodes[[x]]$label <<- as.character(graph$x$nodes[[x]]$id)
})
}
}
# if(!"group"%in%colnames(graph$x$nodes)){
# if(is.data.frame(graph$x$nodes)){
# graph$x$nodes$group <- 1
# } else if(is.list(graph$x$nodes)){
# ctrl <- lapply(1:length(graph$x$nodes), function(x){
# graph$x$nodes[[x]]$group <<- 1
# })
# }
# }
}
#############################
# nodesIdSelection
#############################
idselection <- list(enabled = FALSE, style = 'width: 150px; height: 26px', useLabels = TRUE, main = "Select by id")
if(is.list(nodesIdSelection)){
if(any(!names(nodesIdSelection)%in%c("enabled", "selected", "style", "values", "useLabels", "main"))){
stop("Invalid 'nodesIdSelection' argument. List can have 'enabled', 'selected', 'style', 'values', 'useLabels', 'main'")
}
if("selected"%in%names(nodesIdSelection)){
if(any(class(graph) %in% "visNetwork")){
if(!nodesIdSelection$selected%in%graph$x$nodes$id ){
stop(nodesIdSelection$selected, " not in data. nodesIdSelection$selected must be valid.")
}
}
idselection$selected <- nodesIdSelection$selected
}
if("enabled"%in%names(nodesIdSelection)){
idselection$enabled <- nodesIdSelection$enabled
}else{
idselection$enabled <- TRUE
}
if("main"%in%names(nodesIdSelection)){
idselection$main <- nodesIdSelection$main
}
if("useLabels"%in%names(nodesIdSelection)){
idselection$useLabels <- nodesIdSelection$useLabels
}else if(any(class(graph) %in% "visNetwork_Proxy")){
idselection$useLabels <- NULL
}
if("style"%in%names(nodesIdSelection)){
idselection$style <- nodesIdSelection$style
}else if(any(class(graph) %in% "visNetwork_Proxy")){
idselection$style <- NULL
}
}else if(is.logical(nodesIdSelection)){
idselection$enabled <- nodesIdSelection
if(any(class(graph) %in% "visNetwork_Proxy")){
idselection$useLabels <- NULL
idselection$style <- NULL
}
}else{
stop("Invalid 'nodesIdSelection' argument")
}
if(idselection$enabled){
if("values"%in%names(nodesIdSelection)){
idselection$values <- nodesIdSelection$values
if(length(idselection$values) == 1){
idselection$values <- list(idselection$values)
}
if("selected"%in%names(nodesIdSelection)){
if(!idselection$selected%in%idselection$values){
stop(idselection$selected, " not in data/selection. nodesIdSelection$selected must be a valid value.")
}
}
}
}
#############################
# selectedBy
#############################
byselection <- list(enabled = FALSE, style = 'width: 150px; height: 26px', multiple = FALSE,
hideColor = 'rgba(200,200,200,0.5)', highlight = FALSE)
if(!is.null(selectedBy)){
if(is.list(selectedBy)){
if(any(!names(selectedBy)%in%c("variable", "selected", "style", "values", "multiple", "hideColor", "main", "sort", "highlight"))){
stop("Invalid 'selectedBy' argument. List can have 'variable', 'selected', 'style', 'values', 'multiple', 'hideColor', 'main', 'sort', 'highlight'")
}
if("selected"%in%names(selectedBy)){
byselection$selected <- as.character(selectedBy$selected)
}
if("hideColor"%in%names(selectedBy)){
byselection$hideColor <- selectedBy$hideColor
}
if("highlight"%in%names(selectedBy)){
byselection$highlight <- selectedBy$highlight
}
if(!"variable"%in%names(selectedBy)){
stop("'selectedBy' need at least 'variable' information")
}
byselection$variable <- selectedBy$variable
if("main" %in% names(selectedBy)){
byselection$main <- selectedBy$main
} else {
byselection$main <- paste0("Select by ", selectedBy$variable)
}
if("style"%in%names(selectedBy)){
byselection$style <- selectedBy$style
}else if(any(class(graph) %in% "visNetwork_Proxy")){
byselection$style <- NULL
}
if("multiple"%in%names(selectedBy)){
byselection$multiple <- selectedBy$multiple
}else if(any(class(graph) %in% "visNetwork_Proxy")){
byselection$multiple <- NULL
}
}else if(is.character(selectedBy)){
byselection$variable <- selectedBy
byselection$main <- paste0("Select by ", selectedBy)
if(any(class(graph) %in% "visNetwork_Proxy")){
byselection$style <- NULL
byselection$multiple <- NULL
}
}else{
stop("Invalid 'selectedBy' argument. Must a 'character' or a 'list'")
}
if(any(class(graph) %in% "visNetwork_Proxy")){
byselection$enabled <- TRUE
if("values"%in%names(selectedBy)){
if(length(selectedBy$values) > 1){
byselection$values <- selectedBy$values
} else {
byselection$values <- list(selectedBy$values)
}
}
if("selected"%in%names(byselection)){
byselection$selected <- byselection$selected
}
}else{
if(!byselection$variable%in%colnames(graph$x$nodes)){
warning("Can't find '", byselection$variable, "' in node data.frame")
}else{
byselection$enabled <- TRUE
byselection$values <- unique(graph$x$nodes[, byselection$variable])
if(byselection$multiple){
byselection$values <- unique(gsub("^[[:space:]]*|[[:space:]]*$", "",
do.call("c",strsplit(as.character(byselection$values), split = ","))))
}
if(any(c("integer", "numeric") %in% class(graph$x$nodes[, byselection$variable]))){
byselection$values <- byselection$values
}else{
byselection$values <- as.character(byselection$values)
}
if("sort"%in%names(selectedBy)){
if(selectedBy$sort){
byselection$values <- sort(byselection$values)
}
} else {
byselection$values <- sort(byselection$values)
}
if("values"%in%names(selectedBy)){
# byselection$values <- intersect(byselection$values, selectedBy$values)
byselection$values <- selectedBy$values
}
if("values"%in%names(byselection)){
if(length(byselection$values) == 1){
byselection$values <- list(byselection$values)
}
}
if("selected"%in%names(byselection)){
if(!byselection$selected%in%byselection$values){
stop(byselection$selected, " not in data/selection. selectedBy$selected must be a valid value.")
}
byselection$selected <- byselection$selected
}
if(!"label"%in%colnames(graph$x$nodes)){
if(is.data.frame(graph$x$nodes)){
graph$x$nodes$label <- ""
} else if(is.list(graph$x$nodes)){
ctrl <- lapply(1:length(graph$x$nodes), function(x){
graph$x$nodes[[x]]$label <<- ""
})
}
}
# if(!"group"%in%colnames(graph$x$nodes)){
# if(is.data.frame(graph$x$nodes)){
# graph$x$nodes$group <- 1
# } else if(is.list(graph$x$nodes)){
# ctrl <- lapply(1:length(graph$x$nodes), function(x){
# graph$x$nodes[[x]]$group <<- 1
# })
# }
# }
}
}
}
}
# x <- list(highlight = highlightNearest, hoverNearest = hoverNearest, degree = degree,
# idselection = idselection, byselection = byselection)
x <- list(highlight = highlight, idselection = idselection, byselection = byselection, collapse = list_collapse)
if(highlight$hoverNearest){
graph <- visInteraction(graph, hover = TRUE)
}
if(any(class(graph) %in% "visNetwork_Proxy")){
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyOptions",data)
if(missing(highlightNearest)){
x$highlight <- NULL
}
if(missing(nodesIdSelection)){
x$idselection <- NULL
}
if(missing(selectedBy)){
x$byselection <- NULL
}
if(missing(collapse)){
x$collapse <- NULL
}
data <- list(id = graph$id, options = x)
graph$session$sendCustomMessage("visShinyCustomOptions",data)
}else{
graph$x <- mergeLists(graph$x, x)
graph$x$options <- mergeLists(graph$x$options, options)
}
graph
}
build_manipulation_table <- function(col, type, id = "node"){
if(length(col) > 0){
table <- paste0('<span id="', id, '-operation" class = "operation">node</span> <br><table style="margin:auto;">')
for(i in 1:length(col)){
add <- paste0('<tr><td>', col[i], '</td><td><input id="', id, "-", col[i], '" type= "', type[i], '" value="new value"></td></tr>')
table <- paste0(table, add)
}
table <- paste0(table, '</table><input type="button" value="save" id="', id, '-saveButton"></button><input type="button" value="cancel" id="', id, '-cancelButton"></button>')
} else {
table <- ""
}
table
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visOptions.R
|
#' Network visualization Physics options
#'
#' Network visualization Physics options. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a visNetwork object
#'@param solver : String. Default to 'barnesHut'. You can select your own solver. Possible options: 'barnesHut', 'repulsion', 'hierarchicalRepulsion', 'forceAtlas2Based'. When setting the hierarchical layout, the hierarchical repulsion solver is automaticaly selected, regardless of what you fill in here.
#'@param maxVelocity : Number. Default to 50. The physics module limits the maximum velocity of the nodes to increase the time to stabilization. This is the maximum value.
#'@param minVelocity : Number. Default to 0.1. Once the minimum velocity is reached for all nodes, we assume the network has been stabilized and the simulation stops.
#'@param timestep : Number. Default to 0.5. The physics simulation is discrete. This means we take a step in time, calculate the forces, move the nodes and take another step. If you increase this number the steps will be too large and the network can get unstable. If you see a lot of jittery movement in the network, you may want to reduce this value a little.
#'
#'@param barnesHut, named list of options
#'\itemize{
#' \item{"theta"}{ : Number. Default to 0.5. This parameter determines the boundary between consolidated long range forces and individual short range forces. To oversimplify higher values are faster but generate more errors, lower values are slower but with less errors.}
#' \item{"gravitationalConstant"}{ : Number. Default to -2000. Gravity attracts. We like repulsion. So the value is negative. If you want the repulsion to be stronger, decrease the value (so -10000, -50000).}
#' \item{"centralGravity"}{ : Number. Default to 0.3. There is a central gravity attractor to pull the entire network back to the center.}
#' \item{"springLength"}{ : Number. Default to 95. The edges are modelled as springs. This springLength here is the the rest length of the spring.}
#' \item{"springConstant"}{ : Number. Default to 0.04. This is how 'sturdy' the springs are. Higher values mean stronger springs.}
#' \item{"damping"}{ : Number. Default to 0.09. Accepted range: [0 .. 1]. The damping factor is how much of the velocity from the previous physics simulation iteration carries over to the next iteration.}
#' \item{"avoidOverlap"}{ : Number. Default to 0. Accepted range: [0 .. 1]. When larger than 0, the size of the node is taken into account. The distance will be calculated from the radius of the encompassing circle of the node for both the gravity model. Value 1 is maximum overlap avoidance.}
#'}
#'
#'@param forceAtlas2Based, named list of options
#'\itemize{
#' \item{"theta"}{ : Number. Default to 0.5. This parameter determines the boundary between consolidated long range forces and individual short range forces. To oversimplify higher values are faster but generate more errors, lower values are slower but with less errors.}
#' \item{"gravitationalConstant"}{ : Number. Default to -50. Gravity attracts. We like repulsion. So the value is negative. If you want the repulsion to be stronger, decrease the value (so -10000, -50000).}
#' \item{"centralGravity"}{ : Number. Default to 0.01. There is a central gravity attractor to pull the entire network back to the center.}
#' \item{"springLength"}{ : Number. Default to 100. The edges are modelled as springs. This springLength here is the the rest length of the spring.}
#' \item{"springConstant"}{ : Number. Default to 0.08. This is how 'sturdy' the springs are. Higher values mean stronger springs.}
#' \item{"damping"}{ : Number. Default to 0.4. Accepted range: [0 .. 1]. The damping factor is how much of the velocity from the previous physics simulation iteration carries over to the next iteration.}
#' \item{"avoidOverlap"}{ : Number. Default to 0. Accepted range: [0 .. 1]. When larger than 0, the size of the node is taken into account. The distance will be calculated from the radius of the encompassing circle of the node for both the gravity model. Value 1 is maximum overlap avoidance.}
#'}
#'
#'@param repulsion, named list of options
#'\itemize{
#' \item{"nodeDistance"}{ : Number. Default to 100. This is the range of influence for the repulsion.}
#' \item{"centralGravity"}{ : Number. Default to 0.2. There is a central gravity attractor to pull the entire network back to the center.}
#' \item{"springLength"}{ : Number. Default to 200. The edges are modelled as springs. This springLength here is the the rest length of the spring.}
#' \item{"springConstant"}{ : Number. Default to 0.05. This is how 'sturdy' the springs are. Higher values mean stronger springs.}
#' \item{"damping"}{ : Number. Default to 0.09. Accepted range: [0 .. 1]. The damping factor is how much of the velocity from the previous physics simulation iteration carries over to the next iteration.}
#'}
#'
#'@param hierarchicalRepulsion, named list of options
#'\itemize{
#' \item{"nodeDistance"}{ : Number. Default to 120. This is the range of influence for the repulsion.}
#' \item{"centralGravity"}{ : Number. Default to 0.0. There is a central gravity attractor to pull the entire network back to the center.}
#' \item{"springLength"}{ : Number. Default to 100. The edges are modelled as springs. This springLength here is the the rest length of the spring.}
#' \item{"springConstant"}{ : Number. Default to 0.01. This is how 'sturdy' the springs are. Higher values mean stronger springs.}
#' \item{"damping"}{ : Number. Default to 0.09. Accepted range: [0 .. 1]. The damping factor is how much of the velocity from the previous physics simulation iteration carries over to the next iteration.}
#' \item{"avoidOverlap"}{ : Number. Default to 0. Accepted range: [0 .. 1]. When larger than 0, the size of the node is taken into account. The distance will be calculated from the radius of the encompassing circle of the node for both the gravity model. Value 1 is maximum overlap avoidance.}
#'}
#'
#'@param stabilization, Just a boolean, or a named list of options
#'\itemize{
#' \item{"enabled"}{ : Boolean. Default to true. Toggle the stabilization. This is an optional property. If undefined, it is automatically set to true when any of the properties of this object are defined.}
#' \item{"iterations"}{ : Number. Default to 1000. The physics module tries to stabilize the network on load up til a maximum number of iterations defined here. If the network stabilized with less, you are finished before the maximum number.}
#' \item{"updateInterval"}{ : Number. Default to 50. When stabilizing, the DOM can freeze. You can chop the stabilization up into pieces to show a loading bar for instance. The interval determines after how many iterations the stabilizationProgress event is triggered.}
#' \item{"onlyDynamicEdges"}{ : Boolean. Default to false. If you have predefined the position of all nodes and only want to stabilize the dynamic smooth edges, set this to true. It freezes all nodes except the invisible dynamic smooth curve support nodes. If you want the visible nodes to move and stabilize, do not use this.}
#' \item{"fit"}{ : Boolean. Default to true. Toggle whether or not you want the view to zoom to fit all nodes when the stabilization is finished.}
#'}
#'
#'@param adaptiveTimestep : Boolean. Default to true. If this is enabled, the timestep will intelligently be adapted (only during the stabilization stage if stabilization is enabled!) to greatly decrease stabilization times. The timestep configured above is taken as the minimum timestep. This can be further improved by using the improvedLayout algorithm.
#'
#'@param wind, Named list. A force that pushes all non-fixed nodes in the given direction. Requires all nodes are connected to nodes which are fixed, otherwise non-attached nodes will keep moving indefinitely.
#'\itemize{
#' \item{"x"}{ : Number. Default to 0. The amount of force to be applied pushing non-fixed nodes to the right (positive value) or to the left (negative value).}
#' \item{"y"}{ : Number. Default to 0. The amount of force to be applied pushing non-fixed nodes downwards (positive value) or upwards (negative value).}
#'}
#'
#'@param enabled : Boolean. Default to true. Toggle the physics system on or off. This property is optional. If you define any of the options below and enabled is undefined, this will be set to true.
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'
#'nodes <- data.frame(id = 1:10)
#'edges <- data.frame(from = round(runif(8)*10), to = round(runif(8)*10))
#'
#'visNetwork(nodes, edges) %>%
#' visPhysics(solver = "repulsion")
#'
#'visNetwork(nodes, edges) %>%
#' visPhysics(solver = "forceAtlas2Based", forceAtlas2Based = list(gravitationalConstant = -10))
#'
#'visNetwork(nodes, edges) %>%
#' visPhysics(stabilization = FALSE)
#'
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visPhysics <- function(graph,
solver = NULL,
maxVelocity = NULL,
minVelocity = NULL,
timestep = NULL,
barnesHut = NULL,
forceAtlas2Based = NULL,
repulsion = NULL,
hierarchicalRepulsion = NULL,
stabilization = NULL,
adaptiveTimestep = NULL,
wind = NULL,
enabled = NULL){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
if(!is.null(solver)){
if(!solver%in%c("barnesHut", "repulsion", "hierarchicalRepulsion", "forceAtlas2Based")){
stop('Invalid "solver". Must be one of "barnesHut", "repulsion", "hierarchicalRepulsion", "forceAtlas2Based"')
}
}
if(length(which(!is.null(c(barnesHut, repulsion, hierarchicalRepulsion, forceAtlas2Based)))) > 1){
stop("You can just use one of barnesHut, repulsion, hierarchicalRepulsion physics")
}
physics <- list()
physics$solver <- solver
physics$maxVelocity <- maxVelocity
physics$minVelocity <- minVelocity
physics$timestep <- timestep
physics$stabilization <- stabilization
physics$adaptiveTimestep <- adaptiveTimestep
physics$enabled <- enabled
physics$wind <- wind
if(!is.null(barnesHut)){
physics$barnesHut <- barnesHut
}
if(!is.null(repulsion)){
physics$repulsion <- repulsion
}
if(!is.null(hierarchicalRepulsion)){
physics$hierarchicalRepulsion <- hierarchicalRepulsion
}
if(!is.null(forceAtlas2Based)){
physics$forceAtlas2Based <- forceAtlas2Based
}
if(any(class(graph) %in% "visNetwork_Proxy")){
options <- list(physics = physics)
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyOptions",data)
}else{
graph$x$options$physics <- physics
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visPhysics.R
|
#' Network visualization redraw method
#'
#' Network visualization redraw method For use redraw() method in a shiny app. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visRedraw <- function(graph){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visRedraw with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id)
graph$session$sendCustomMessage("visShinyRedraw", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visRedraw.R
|
#' Function to remove edges from network, with shiny only.
#'
#' Function to remove edges from network, with shiny only.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param id : vector of id, edges to remove
#'@param legend : Boolean. Remove edges on legend ? Default to FALSE
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visRemoveEdges <- function(graph, id, legend = FALSE){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visRemoveEdges with visNetwork object. Only within shiny & using visNetworkProxy")
}
if(!is.null(id)){
if(length(id) == 1){
id <- list(id)
}
}
data <- list(id = graph$id, rmid = id, legend = legend)
graph$session$sendCustomMessage("visShinyRemoveEdges", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visRemoveEdges.R
|
#' Function to remove nodes from network, with shiny only.
#'
#' Function to remove nodes from network, with shiny only.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param id : vector of id, nodes to remove
#'@param updateOptions : Boolean. Update options (nodesIdSelection & selectedBy) if needed ? Default to TRUE.
#'@param legend : Boolean. Remove nodes on legend ? Default to FALSE
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visRemoveNodes <- function(graph, id, updateOptions = TRUE, legend = FALSE){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visRemoveNodes with visNetwork object. Only within shiny & using visNetworkProxy")
}
if(!is.null(id)){
if(length(id) == 1){
id <- list(id)
}
}
data <- list(id = graph$id, rmid = id, updateOptions = updateOptions, legend = legend)
graph$session$sendCustomMessage("visShinyRemoveNodes", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visRemoveNodes.R
|
#' Save a a visNetwork object to an HTML file
#'
#' Save a a visNetwork object to an HTML file for sharing with others. The HTML can
#' include it's dependencies in an adjacent directory or can bundle all
#' dependencies into the HTML file (via base64 encoding).
#'
#' @param graph : a visNetwork object
#' @param file : File to save HTML into. See \link{saveWidget}
#' @param selfcontained : Whether to save the HTML as a single self-contained file (with external resources base64 encoded) or a file with external resources placed in an adjacent directory.
#' @param background : Text string giving the html background color of the widget. Defaults to white.
#'
#'
#' @examples
#'
#'\dontrun{
#'
#'nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
#'edges <- data.frame(from = c(1,2), to = c(2,3))
#'
#'network <- visNetwork(nodes, edges)
#'network
#'
#'network %>% visSave(file = "network.html", background = "black")
#'
#'# same as
#'visSave(network, file = "network.html", background = "black")
#'
#'}
#' @export
#'
#' @seealso \link{visExport}
#'
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visSave <- function(graph, file, selfcontained = TRUE, background = "white") {
htmlwidgets::saveWidget(graph, file, selfcontained = selfcontained, background = background)
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visSave.R
|
#' Function to select edge(s) from network, with shiny only.
#'
#' Function to select edges(s) from network, with shiny only.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param id : vector of id, edges(s) to select
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visSelectEdges <- function(graph, id){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visSelectEdges with visNetwork object. Only within shiny & using visNetworkProxy")
}
if(!is.null(id)){
if(length(id) == 1){
id <- list(id)
}
}
data <- list(id = graph$id, selid = id)
graph$session$sendCustomMessage("visShinySelectEdges", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visSelectEdges.R
|
#' Function to select node(s) from network, with shiny only.
#'
#' Function to select node(s) from network, with shiny only.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param id : vector of id, node(s) to select
#'@param highlightEdges : Boolean. highlight Edges also ? Default to TRUE
#'@param clickEvent : Boolean. Launch click event ? (highlightNearest for example) Default to TRUE
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visSelectNodes <- function(graph, id, highlightEdges = TRUE, clickEvent = TRUE){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visSelectNodes with visNetwork object. Only within shiny & using visNetworkProxy")
}
stopifnot(is.logical(highlightEdges))
stopifnot(is.logical(clickEvent))
if(!is.null(id)){
if(length(id) == 1){
id <- list(id)
}
}
data <- list(id = graph$id, selid = id, highlightEdges = highlightEdges, clickEvent = clickEvent)
graph$session$sendCustomMessage("visShinySelectNodes", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visSelectNodes.R
|
#' Network visualization setData method
#'
#' For use setData() method in a shiny app. For full documentation, have a look at \link{visDocumentation}.
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param nodes : data.frame with nodes informations. Needed at least column "id". See \link{visNodes}
#' @param edges : data.frame with edges informations. Needed at least columns "from" and "to". See \link{visEdges}
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visSetData <- function(graph, nodes = NULL, edges = NULL){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visSetData with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, nodes = nodes, edges = edges)
graph$session$sendCustomMessage("visShinySetData", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visSetData.R
|
#' Network visualization full options setter
#'
#' Network visualization full options setter. Using this function, you can pass all network options you want,
#' respecting the library format rather than use \link{visNodes}, \link{visEdges}, \link{visGroups}....
#' There is no control, so it's at your own risk !
#'
#' @param graph : a visNetwork object
#' @param options : a named list with all options you want to add to your network.
#'
#' @examples
#' nodes <- data.frame(id = 1:3)
#' edges <- data.frame(from = c(1,2), to = c(1,3))
#'
#' # using visNetwork functions
#' visNetwork(nodes, edges) %>% visNodes(shape = "square", color = "red") %>%
#' visEdges(arrows = "to")
#'
#' # directly use visSetOptions
#' visNetwork(nodes, edges) %>%
#' visSetOptions(options = list(nodes = list(shape = "square", color = "red"),
#' edges = list(arrows = "to")))
#'
#'
#'
#' @export
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visSetOptions <- function(graph, options = NULL){
if(!any(class(graph) %in% c("visNetwork", "visNetwork_Proxy"))){
stop("graph must be a visNetwork or a visNetworkProxy object")
}
if(any(class(graph) %in% "visNetwork_Proxy")){
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyOptions", data)
}else{
graph$x$options <- mergeLists(graph$x$options, options)
}
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visSetOptions.R
|
#' Function to select edge(s) / node(s) from network, with shiny only.
#'
#' Function to select edge(s) / node(s) from network, with shiny only.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param nodesId : vector of id, nodes(s) to select
#'@param edgesId : vector of id, edges(s) to select
#'@param unselectAll : Boolean. Unselect all nodes & edges before current selection ? Default to TRUE
#'@param highlightEdges : Boolean. highlight Edges also ? Default to TRUE
#'@param clickEvent : Boolean. Launch click event ? (highlightNearest for example) Default to TRUE
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visSetSelection <- function(graph, nodesId = NULL, edgesId = NULL, unselectAll = TRUE,
highlightEdges = TRUE, clickEvent = TRUE){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visSetSelection with visNetwork object. Only within shiny & using visNetworkProxy")
}
if(!is.null(nodesId)){
if(length(nodesId) == 1){
nodesId <- list(nodesId)
}
}
if(!is.null(edgesId)){
if(length(edgesId) == 1){
edgesId <- list(edgesId)
}
}
data <- list(id = graph$id, selection = list(nodes = nodesId, edges = edgesId),
options = list(unselectAll = unselectAll, highlightEdges = highlightEdges), clickEvent = clickEvent)
graph$session$sendCustomMessage("visShinySetSelection", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visSetSelection.R
|
#' Set title, subtitle, and footer using \code{visNetworkProxy}
#'
#' @param graph : a \code{\link{visNetworkProxy}} object
#' @param main : For add a title. Character or a named list.
#' \itemize{
#' \item{"text"}{ : Character. Title.}
#' \item{"style"}{ : Optional. Character. HTML style of title.}
#' \item{'hidden'}{ : Optional. Boolean. Force title to be hidden}
#' }
#'
#' @param submain : For add a subtitle. Character or a named list.
#' \itemize{
#' \item{"text"}{ : Character. Subtitle.}
#' \item{"style"}{ : Optional. Character. HTML style of submain.}
#' \item{'hidden'}{ : Optional. Boolean. Force submain to be hidden}
#' }
#'
#' @param footer : For add a footer. Character or a named list.
#' \itemize{
#' \item{"text"}{ : Character. footer.}
#' \item{"style"}{ : Optional. Character. HTML style of footer.}
#' \item{'hidden'}{ : Optional. Boolean. Force footer to be be hidden}
#' }
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visSetTitle <- function(graph, main = NULL, submain = NULL, footer = NULL){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visSetTitle with visNetwork object. Only within shiny & using visNetworkProxy")
}
# main
if(!is.null(main)){
if(is.list(main)){
if(any(!names(main)%in%c("text", "style", "hidden"))){
stop("Invalid 'main' argument")
}
if(!"hidden"%in%names(main)){
main$hidden <- FALSE
}
}else if(!inherits(main, "character")){
stop("Invalid 'main' argument. Not a character")
}else {
main <- list(text = main, hidden = FALSE)
}
}
# submain
if(!is.null(submain)){
if(is.list(submain)){
if(any(!names(submain)%in%c("text", "style", "hidden"))){
stop("Invalid 'submain' argument")
}
if(!"hidden"%in%names(submain)){
submain$hidden <- FALSE
}
}else if(!inherits(submain, "character")){
stop("Invalid 'submain' argument. Not a character")
}else {
submain <- list(text = submain, hidden = FALSE)
}
}
# footer
if(!is.null(footer)){
if(is.list(footer)){
if(any(!names(footer)%in%c("text", "style", "hidden"))){
stop("Invalid 'footer' argument")
}
if(!"hidden"%in%names(footer)){
footer$hidden <- FALSE
}
}else if(!inherits(footer, "character")){
stop("Invalid 'footer' argument. Not a character")
}else {
footer <- list(text = footer, hidden = FALSE)
}
}
data <- list(id = graph$id, main = main, submain = submain, footer = footer)
graph$session$sendCustomMessage("visShinySetTitle", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visSetTitle.R
|
#' Network visualization stabilize method
#'
#' For use stabilize() method in a shiny app. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param iterations : Optional. If wanted, the number of iterations
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visStabilize <- function(graph, iterations = NULL){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visFit with visNetwork object. Only within shiny & using visNetworkProxy")
}
options <- list()
options$iterations <- iterations
data <- list(id = graph$id, options = options)
graph$session$sendCustomMessage("visShinyStabilize", data)
graph
}
#' Network visualization startSimulation method
#'
#' For use startSimulation() method in a shiny app. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
visStartSimulation <- function(graph){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visFit with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id)
graph$session$sendCustomMessage("StartSimulation", data)
graph
}
#' Network visualization stopSimulation method
#'
#' For use stopSimulation() method in a shiny app. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
visStopSimulation <- function(graph){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visFit with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id)
graph$session$sendCustomMessage("StopSimulation", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visStabilize.R
|
#' Visualize Recursive Partitioning and Regression Trees (rpart object)
#'
#' Visualize Recursive Partitioning and Regression Trees \code{rpart}. Have a look to \link{visTreeEditor} to edity and get back network, or to \link{visTreeModuleServer} to use custom tree module in R
#'
#' @param object \code{rpart}, rpart object
#' @param data \code{data.frame}, adding mini-graphics in tooltips using \code{sparkline} and \code{tooltipColumns} ?
#' @param tooltipColumns \code{numeric}, indice of columns used in tooltip. All by default.
#' So, we add boxplot / pie focus on sub-population vs all population using \code{sparkline} package. \code{NULL} to disable.
#' @param main Title. See \link{visNetwork}
#' @param submain Subtitle. See \link{visNetwork}
#' @param footer Footer. See \link{visNetwork}
#' @param direction \code{character}, The direction of the hierarchical layout.
#' The available options are: UD, DU, LR, RL. To simplify:
#' up-down, down-up, left-right, right-left. Default UD. See \link{visHierarchicalLayout}
#' @param nodesPopSize \code{boolean}, nodes sizes depends on population ? Default to FALSE
#' @param fallenLeaves \code{boolean} leaf nodes at the bottom of the graph ? Default to FALSE
#' @param nodesFontSize \code{numeric}, size of labels of nodes. Default to 16
#' @param edgesFontSize \code{numeric}, size of labels of edges Default to 14
#' @param legendFontSize \code{numeric}, size of labels of nodes in legend. Default to 16
#' @param legendNodesSize \code{numeric}, size of nodes in legend. Default to 22
#' @param edgesFontAlign \code{character}, for edges only. Default tp 'horizontal'. Possible options: 'horizontal' (Default),'top','middle','bottom'. See \link{visEdges}
#' @param colorVar \code{character}, colors to use or \code{data.frame} To set color of variables. 2 columns :
#' \itemize{
#' \item{"variable"}{ : names of variables}
#' \item{"color"}{ : colors (in hexa). See examples}
#' }
#' @param colorY if classification tree : \code{character} colors to use or \code{data.frame} 2 columns :
#' \itemize{
#' \item{"modality"}{ : levels of Y}
#' \item{"color"}{ : colors (in hexa)}
#' }
#' if regression tree : \code{character}, 2 colors (min and max, in hexa)
#' @param colorEdges \code{character}, color of edges, in hexa. Default to #8181F7
#' @param legend \code{boolean}, add legend ? Default TRUE. \link{visLegend}
#' @param legendWidth \code{numeric}, legend width, between 0 and 1. Default 0.1
#' @param legendNcol \code{numeric}, number of columns in legend. Default 1
#' @param legendPosition \code{character}, one of "left" (Default) or "right"
#' @param highlightNearest \code{list}, Highlight nearest nodes. See \link{visOptions}
#' @param collapse \code{list}, collapse or not using double click on a node ? See \link{visOptions}
#' @param updateShape \code{boolean}, in case of collapse, udpate cluster node shape as terminal node ? Default to TRUE
#' @param tooltipDelay \code{numeric}, delay for tooltips in millisecond. Default 500
#' @param rules \code{boolean}, add rules in tooltips ? Default to TRUE
#' @param simplifyRules \code{boolean}, simplify rules writing
#' @param digits \code{numeric}, number of digits. Default to 3
#' @param height \code{character}, default to "600px"
#' @param width \code{character}, default to "100\%"
#' @param minNodeSize \code{numeric}, in case of \code{nodesPopSize}, minimum size of a node. Default to 15. Else, nodes size is minNodeSize + maxNodeSize / 2
#' @param maxNodeSize \code{numeric}, in case of \code{nodesPopSize}, maximum size of a node. Default to 30. Else, nodes size is minNodeSize + maxNodeSize / 2
#' @param shapeVar \code{character}, shape for variables nodes See \link{visNodes}
#' @param shapeY \code{character}, shape for terminal nodes See \link{visNodes}
#' @param export \code{boolean}, add export button. Default to TRUE
#'
#' @return a visNetwork object
#'
#' @seealso \link{visTreeEditor}, \link{visTreeModuleServer}, \link{visNetworkEditor}
#'
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
#'
#' @examples
#'
#' \dontrun{
#'
#' library(rpart)
#'
#' # Basic classification tree
#' res <- rpart(Species~., data=iris)
#' visTree(res, data = iris, main = "Iris classification Tree")
#'
#' # Basic regression tree
#' res <- rpart(Petal.Length~., data=iris)
#' visTree(res, edgesFontSize = 14, nodesFontSize = 16)
#'
#' # Complex tree
#' data("solder")
#' res <- rpart(Opening~., data = solder, control = rpart.control(cp = 0.00005))
#' visTree(res, data = solder, nodesPopSize = TRUE, minNodeSize = 10,
#' maxNodeSize = 30, height = "800px")
#'
#' # ----- Options
#' res <- rpart(Opening~., data = solder, control = rpart.control(cp = 0.005))
#'
#' # fallen leaves + align edges label & size
#' visTree(res, fallenLeaves = TRUE, height = "500px",
#' edgesFontAlign = "middle", edgesFontSize = 20)
#'
#' # disable rules in tooltip, and render tooltip faster
#' # enable hover highlight
#' visTree(res, rules = FALSE, tooltipDelay = 0,
#' highlightNearest = list(enabled = TRUE, degree = list(from = 50000, to = 0),
#' hover = TRUE, algorithm = "hierarchical"))
#'
#' # Change color with data.frame
#' colorVar <- data.frame(variable = names(solder),
#' color = c("#339933", "#b30000","#4747d1","#88cc00", "#9900ff","#247856"))
#'
#' colorY <- data.frame(modality = unique(solder$Opening),
#' color = c("#AA00AA", "#CDAD15", "#213478"))
#'
#' visTree(res, colorEdges = "#000099", colorVar = colorVar, colorY = colorY)
#'
#' # Change color with vector
#' visTree(res, colorEdges = "#000099",
#' colorVar = substring(rainbow(6), 1, 7),
#' colorY = c("blue", "green", "orange"))
#'
#'
#' # Use visNetwork functions to add more options
#' visTree(res) %>%
#' visOptions(highlightNearest = TRUE)
#'
#'
#' }
#'
#' @export
#'
#' @importFrom grDevices hcl
#' @importFrom grDevices colorRamp
#' @importFrom grDevices rgb
#'
visTree <- function(object,
data = NULL,
tooltipColumns = if(!is.null(data)){1:ncol(data)} else {NULL},
main = "",
submain = "",
footer = "",
direction = "UD",
fallenLeaves = FALSE,
rules = TRUE,
simplifyRules = TRUE,
shapeVar = "dot",
shapeY = "square",
colorVar = NULL,
colorY = NULL,
colorEdges = "#8181F7",
nodesFontSize = 16,
edgesFontSize = 14,
edgesFontAlign = "horizontal",
legend = TRUE,
legendNodesSize = 22,
legendFontSize = 16,
legendWidth = 0.1,
legendNcol = 1,
legendPosition = "left",
nodesPopSize = FALSE,
minNodeSize = 15,
maxNodeSize = 30,
highlightNearest = list(enabled = TRUE,
degree = list(from = 50000, to = 0), hover = FALSE,
algorithm = "hierarchical"),
collapse = list(enabled = TRUE, fit = TRUE, resetHighlight = TRUE,
clusterOptions = list(fixed = TRUE, physics = FALSE)),
updateShape = TRUE,
tooltipDelay = 500,
digits = 3,
height = "600px",
width = "100%",
export = TRUE){
# controls
stopifnot("rpart" %in% class(object))
stopifnot("character" %in% class(direction))
stopifnot(direction %in% c("UD", "LR", "RL", "DU"))
stopifnot(length(direction) == 1)
stopifnot("logical" %in% class(nodesPopSize))
stopifnot("numeric" %in% class(minNodeSize) | "integer" %in% class(minNodeSize))
stopifnot("numeric" %in% class(maxNodeSize) | "integer" %in% class(maxNodeSize))
stopifnot("logical" %in% class(fallenLeaves))
stopifnot("logical" %in% class(simplifyRules))
stopifnot("numeric" %in% class(nodesFontSize) | "integer" %in% class(nodesFontSize))
stopifnot("numeric" %in% class(edgesFontSize) | "integer" %in% class(edgesFontSize))
stopifnot("numeric" %in% class(legendFontSize) | "integer" %in% class(legendFontSize))
stopifnot("character" %in% class(edgesFontAlign))
if(!is.null(colorVar)){
stopifnot(any(c("data.frame", "character") %in% class(colorVar)))
}
if(!is.null(colorY)){
if(object$method == "class"){
stopifnot(any(c("data.frame", "character") %in% class(colorY)))
}
if(object$method == "anova"){
stopifnot("character"%in%class(colorY))
stopifnot(length(colorY) <= 2)
}
}
if(!is.null(colorEdges)){
stopifnot("character" %in% class(colorEdges))
}
stopifnot("logical" %in% class(legend))
stopifnot("numeric" %in% class(legendWidth) | "integer" %in% class(legendWidth))
stopifnot("numeric" %in% class(legendNcol) | "integer" %in% class(legendNcol))
stopifnot("character" %in% class(legendPosition))
stopifnot(any(c("logical", "list") %in% class(highlightNearest)))
stopifnot(any(c("logical", "list") %in% class(collapse)))
stopifnot("numeric" %in% class(tooltipDelay)| "integer" %in% class(tooltipDelay))
stopifnot("logical" %in% class(rules))
stopifnot("numeric" %in% class(digits)| "integer" %in% class(digits))
stopifnot("character" %in% class(height))
stopifnot("character" %in% class(width))
stopifnot("character" %in% class(shapeVar))
stopifnot("character" %in% class(shapeY))
if(!is.null(tooltipColumns)){
if(class(tooltipColumns) %in% c("character", "factor")){
tooltipColumns <- which(tooltipColumns %in% colnames(data))
}
stopifnot(class(tooltipColumns)[1] %in% c("numeric", "integer"))
stopifnot(!is.null(data))
stopifnot(max(tooltipColumns) <= ncol(data))
which_character <- which(sapply(data[, tooltipColumns, drop = FALSE],
function(x) class(x)[1]) %in% "character")
if(length(which_character) > 0){
for(i in tooltipColumns[which_character]){
data[, i] <- as.factor(data[, i])
}
}
}
if(!is.null(tooltipColumns) | rules){
if(!requireNamespace("sparkline", quietly = TRUE)){
stop("'sparkline' package is needed for this function")
}
}
# ------------------------------
# get information from rpart object
rpartNodesNames <- row.names(object$frame)
infoClass <- NULL
parentsDec <- list(lapply(rpartNodesNames, function(X)(.parent(as.numeric(X)))))
infoVar <- object$frame$var
infoRules <- .vis_give_rules(object)
detailRules <- .rpart_lists(object)
colLabels <- attributes(object$terms)$term.labels
colClass <- attributes(object$terms)$dataClasses
colClass <- colClass[names(colClass)%in%colLabels]
if(length(rpartNodesNames) > 1){
rpartHier <- sapply(as.numeric(rpartNodesNames[2:length(rpartNodesNames)]), function(X){
info <- .parent(X)
list(info[length(info)-1], info[length(info)], length(info))
})
from <- unlist(rpartHier[1,])
to <- unlist(rpartHier[2,])
level <- c(1, unlist(rpartHier[3,]))
# ------------------------------
# build edge info (label + tootip)
edgesLabels <- character(length(to))
edgesTooltip <- character(length(to))
lapply(1:length(to), function(i){
cur_rule <- strsplit(infoRules[paste0("Node", to[i])], ",")[[1]]
sens <- substr(cur_rule, 1, 1)
ind_rule <- as.numeric(substr(cur_rule, 2, nchar(cur_rule)))
rule <- detailRules[[sens]][[ind_rule]]
operator <- attributes(rule)$compare
# if(names(operator) %in% names(colClass[which(colClass %in% c("factor", "character", "ordered"))])){
if(operator %in% "="){
operator <- NULL
edgesLabels[i] <<- paste(rule, collapse = ", ")
}else{
rule <- round(rule, digits)
edgesLabels[i] <<- paste(operator, paste(rule, collapse = ", "))
}
edgesTooltip[i] <<- paste0('<div style="text-align:center;"><b>', names(attr(rule, "compare")), "</b></div>",
paste0('<div style="text-align:center;">', operator, rule, "</div>", collapse = ""))
invisible()
})
edgesLabelsFull <- edgesLabels
formatLabels <- function(x){
ifelse(nchar(x) > 10, paste0(substr(x, 1, 7), "..."), x)
}
edgesLabels <- sapply(edgesLabels, formatLabels)
} else {
level <- 1
}
# ------------------------------
# nodes
if(length(rpartNodesNames) > 1){
nodes_pop <- object$frame$n[match(to, rpartNodesNames)]
} else {
nodes_pop <- object$frame$n
}
nodes_var <- as.character(infoVar)
nodes_var_color <- nodes_var[nodes_var != "<leaf>"]
shape <- ifelse(infoVar != "<leaf>", shapeVar, shapeY)
SortLabel <- sort(unique(nodes_var_color))
colorVar <- .generateVarColor(colorVar, nodes_var_color, SortLabel)
nodes_color <- as.character(colorVar$color[match(nodes_var, colorVar$variable)])
# get stats for nodes (mean / variance / proba)
statsNodes <- NULL
# Classification TREE
if(!is.null(attributes(object)$ylevels)){
infoClass <- attributes(object)$ylevels
nlevelsClass <- length(infoClass)
probaClass <- object$frame[,"yval2"]
effectif <- data.frame(probaClass[,2:(nlevelsClass+1), drop = F])
probs <- data.frame(probaClass[,(nlevelsClass+2):(ncol(probaClass)-1), drop = F])
probsHtml <- probs
for(i in 1:length(infoClass)){
probsHtml[,i] <- paste0(infoClass[i], " : <b>",
round(probsHtml[,i], digits)*100, "%</b>",
" (", effectif[,i], ")")
}
statsNodes <- apply(probsHtml, 1, function(x){paste0(x, collapse = "<br>")})
}else{
# Regression TREE
varNodes <- round(object$frame$dev/(object$frame$n - 1),digits)
varNodes[which(varNodes == Inf)] <- NA
statsNodes <- paste0("Mean : <b>" , round(object$frame$yval,digits),
"</b><br>Variance : <b>",varNodes, "</b>")
}
# ------------------------------
# Build rules for tooltip
tooltipRules <- list(NULL)
if(length(parentsDec[[1]]) > 1){
for(i in 2:length(parentsDec[[1]])){
use <- parentsDec[[1]][[i]]
varDecisions <- nodes_var[match(as.character(use[-length(use)]), rpartNodesNames)]
decisionsrules <- edgesLabelsFull[match(as.character(use), rpartNodesNames)-1]
varDecisionBegin <- unique(varDecisions)
if(simplifyRules){
filtre <- ifelse(colClass[varDecisions]%in% c("character", "factor", "ordered"),
varDecisions,
paste0(varDecisions, substr(decisionsrules, 1 ,1)))
tabFiltre <- table(filtre) > 1
if(length(which(tabFiltre))>0){
filtres <- names(tabFiltre)[which(tabFiltre)]
filtreOut <- NULL
for(j in filtres){
filtreOut <- c(filtreOut, max(which(j== filtre)))
}
keeprules <- sort(c(which(!filtre%in%filtres), filtreOut))
varDecisions <- varDecisions[keeprules]
decisionsrules <- decisionsrules[keeprules]
}
filtre <- varDecisions
varDecisionsOrder <- varDecisions
tabFiltre <- table(filtre)>1
if(length(which(tabFiltre))>0){
filtres <- names(tabFiltre)[which(tabFiltre)]
for(j in filtres){
rulesNumSimpl <- decisionsrules[which(varDecisions == j)]
down <- which(substr(rulesNumSimpl,1,1) == ">")
newLib <- paste0("", substr(rulesNumSimpl[down], 4, nchar(rulesNumSimpl[down])),
" <= <b>", j, "</b> < ", substr(rulesNumSimpl[-down], 3,
nchar(rulesNumSimpl[-down])))
decisionsrules <- decisionsrules[-which(varDecisions == j)]
varDecisions <- varDecisions[-which(varDecisions == j)]
varDecisionsOrder <- varDecisionsOrder[-which(varDecisionsOrder == j)]
varDecisionsOrder <- c(varDecisionsOrder, j)
varDecisions <- c(varDecisions, "")
decisionsrules <- c(decisionsrules, newLib)
}
}
varDecisions <- varDecisions[match(varDecisionBegin, varDecisionsOrder )]
decisionsrules <- decisionsrules[match(varDecisionBegin, varDecisionsOrder )]
}
tooltipRules[[i]] <- paste0(paste("<b>",varDecisions, "</b>", decisionsrules), collapse = "<br>")
}
}
# ------------------------------
# Sparklines for nodes
labelComplete <- NULL
if(!is.null(data) & !is.null(tooltipColumns)){
data <- data[, tooltipColumns, drop = FALSE]
nodesNames <- as.integer(rownames(object$frame))
classDtaIn <- unlist(lapply(data, function(X){class(X)[1]}))
classDtaIn <- classDtaIn%in%c("numeric", "integer")
dataNum <- data[,classDtaIn, drop = FALSE]
if(ncol(dataNum) > 0){
minPop <- apply(dataNum, 2, min, na.rm = TRUE)
maxPop <- apply(dataNum, 2, max, na.rm = TRUE)
meanPop <- colMeans(dataNum, na.rm = TRUE)
popSpkl <- apply(dataNum,2, function(X){
.addSparkLineOnlyJs(X, type = "box")
})
labelComplete <- sapply(nodesNames, function(Z){
.giveLabelsFromDfWhichInvisible(subsetRpart(object, dataNum, Z),
popSpkl, minPop, maxPop, meanPop)
})
}
dataOthr <- data[,!classDtaIn, drop = FALSE]
if(ncol(dataOthr) > 0){
popSpkl <- apply(dataOthr,2, function(X){
Y <- sort(table(X))
spl <- .addSparkLineOnlyJs(Y , type = "pie", labels = names(Y))
if(length(Y) > 1){
Y <- data.frame(Y)
} else {
Y <- data.frame(X = names(Y), Freq = Y)
}
Y$X <- ifelse(nchar(as.character(Y$X) ) > 9,
paste0(substr(Y$X, 1, 8), "..."), as.character(Y$X))
modP <- Y$X[length(Y$X)]
paste0(spl, " On pop. (mode: <b>", modP, "</b>)")
})
namOrder <- lapply(dataOthr, function(X){
names(sort(table(X)))
})
labelComplete <- paste(labelComplete, sapply(nodesNames, function(Z){
.giveLabelsFromDfChrInvisible(subsetRpart(object, dataOthr, Z),
popSpkl, namOrder)} ) )
}
labelComplete <- paste0('<hr class = "rPartvisNetwork">
<div class ="showOnMe"><div style="text-align:center;"><U style="color:blue;" onmouseover="this.style.cursor=\'pointer\';" onmouseout="this.style.cursor=\'default\';">Details</U></div>
<div class="showMeRpartTTp" style="display:none;margin-top: -15px">
',labelComplete,
'</script>',
'<script type="text/javascript">',
'$(document).ready(function(){
$(".showOnMe").click(function(){
$(".showMeRpartTTp").toggle();
$.sparkline_display_visible();
});
});</script>','</div></div>')
}
# ------------------------------
# Terminal nodes colors
ind_terminal <- which(nodes_var == "<leaf>")
if(!is.null(attributes(object)$ylevels)){
# Classification tree
listColorY <- .generateYColor(object, colorY, nodes_var, digits = digits, infoClass = infoClass, probs = probs)
colNodClust <- as.character(listColorY$colorY$color[match(listColorY$vardecidedClust, listColorY$colorY$modality)])
nodes_color[ind_terminal] <- colNodClust[ind_terminal]
nodes_var[ind_terminal] <- listColorY$vardecidedClust[ind_terminal]
}else{
# regression tree
listColorY <- .generateYColor(object, colorY, nodes_var, digits = digits)
# for legend color
colorMin <- grDevices::rgb(listColorY$colRamp(0), maxColorValue=255)
colorMax <- grDevices::rgb(listColorY$colRamp(1), maxColorValue=255)
# terminal nodes
nodes_color[ind_terminal] <- listColorY$colorTerm[ind_terminal]
classTerminal <- round(object$frame$yval, digits)
nodes_var[ind_terminal] <- listColorY$vardecidedClust[ind_terminal]
# cluster
colNodClust <- listColorY$colorTerm
}
if(rules) {
idToSample <- length(tooltipRules)
idS <- sapply(1:idToSample, function(X){paste0(sample(LETTERS, 15), collapse = "")})
idS <- paste0("myIdToDisplay", idS)
# <div onclick="toggle_visibility(\'',idS,'\')">
# <U>RULES</U></div><div id="',idS,'">',
# tooltipRules,'</div>
finalHtmlRules <- paste0(
'<hr class = "rPartvisNetwork">
<div class ="showOnMe2"><div style="text-align:center;"><U style="color:blue;" onmouseover="this.style.cursor=\'pointer\';" onmouseout="this.style.cursor=\'default\';">Rules</U></div>
<div class="showMeRpartTTp2" style="display:none;">
',tooltipRules,
'</script>',
'<script type="text/javascript">',
'$(document).ready(function(){
$(".showOnMe2").click(function(){
$(".showMeRpartTTp2").toggle();
$.sparkline_display_visible();
});
});</script>','</div></div>
')
}else{
finalHtmlRules <- ""
}
finalNodesTooltip <- paste0(
'<div style="text-align:center;">', "N : <b>",
round(object$frame$n/object$frame$n[1],digits)*100,
"%</b> (", object$frame$n,")<br>", "Complexity : <b>",
round(object$frame$complexity, digits),
"</b><br>", statsNodes,
ifelse(!unlist(lapply(tooltipRules, is.null)), finalHtmlRules, ""), '</div>',
labelComplete)
# ------------------------------
# Nodes size on population
value = object$frame$n
if(nodesPopSize){
minNodeSize = minNodeSize
maxNodeSize = maxNodeSize
}else{
minNodeSize = (minNodeSize + maxNodeSize) / 2
maxNodeSize = minNodeSize
}
# ------------------------------
# Legend
legendX <- lapply(SortLabel[SortLabel != "<leaf>"], function(x){
col <- as.character(colorVar$color[match(x, colorVar$variable)])
list(label = x, color = col, shape = shapeVar, size = legendNodesSize,
Leaf = 0, font.size = legendFontSize)
})
legendY <- lapply(infoClass, function(X){
# if(is.null(colorY)){
# col <- colorTerm[which(infoClass== X)]
# }else{
col <- as.character(listColorY$colorY$color[match(X, listColorY$colorY$modality)])
# }
list(label = X, color = col, shape = shapeY, size = legendNodesSize,
Leaf = 1, font.size = legendFontSize)
})
legendFinal <- do.call(rbind,(lapply(c(legendX, legendY), data.frame)))
if(!is.null(legendFinal)){
legendFinal$id <- 10000:(10000 + (nrow(legendFinal))-1)
}
# ------------------------------
# Final data for visNetwork
nodes <- data.frame(id = as.numeric(rpartNodesNames), label =nodes_var,
level = level, color = nodes_color, value = value,
shape = shape, title = finalNodesTooltip, fixed = TRUE,
colorClust = colNodClust, labelClust = listColorY$vardecidedClust, Leaf = 0,
font.size = nodesFontSize, scaling.min = minNodeSize, scaling.max = maxNodeSize)
nodes$Leaf[ind_terminal] <- 1
if(fallenLeaves){
nodes$level[which(nodes$shape %in% shapeY)] <- max(nodes$level)
}
if(length(rpartNodesNames) > 1){
smooth <- list(enabled = TRUE, type = "cubicBezier", roundness = 0.5)
edges <- data.frame(id = paste0("edge", 1:length(from)),from = from, to = to, label = edgesLabels,
value = nodes_pop, title = edgesTooltip, color = colorEdges,
font.size = edgesFontSize, font.align = edgesFontAlign, smooth = smooth)
} else {
edges <- NULL
}
# ------------------------------
# Coordinate
# if(coordinates){
# rpartcoParams <- list(uniform = TRUE, branch = 0.2, nspace = 0.2, minbranch = 0.3)
# Xp <- rpart:::rpartco(object, rpartcoParams)$x
# nodes$x <- Xp * 100
# nodes$y <- nodes$level * 150
# nodes$y <- nodes$y - mean(nodes$y)
# nodes$x <- nodes$x - mean(nodes$x)
#
# intervalPositionX <- max(nodes$x)
# CorrectPosition <- legendWidth*intervalPositionX
# nodes$x <- nodes$x + CorrectPosition / 8
# nodes$x <- nodes$x / (1 + legendWidth)
# }
tree <- visNetwork(nodes = nodes, edges = edges, height = height, width = width, main = main,
submain = submain, footer = footer) %>%
visHierarchicalLayout(direction = direction) %>%
visOptions(highlightNearest = highlightNearest, collapse = collapse) %>%
visInteraction(tooltipDelay = tooltipDelay,
dragNodes = FALSE, selectConnectedEdges = FALSE,
tooltipStyle = 'position: fixed;visibility:hidden;padding: 5px;
white-space: nowrap;
font-family: cursive;font-size:12px;font-color:purple;background-color: #E6E6E6;
border-radius: 15px;') %>%
visEdges(scaling = list(label = list(enabled = FALSE))) %>%
visEvents(type = "once", stabilized = "function() {
this.setOptions({layout:{hierarchical:false}, physics:{solver:'barnesHut', enabled:true, stabilization : false}, nodes : {physics : false, fixed : true}});
}")
if(!is.null(legendFinal)){
tree <- visLegend(tree, addNodes = legendFinal, useGroups = FALSE, enabled = legend,
width = legendWidth, ncol = legendNcol, position = legendPosition)
}
# rajout informations class tree
tree$x$tree <- list(updateShape = updateShape, shapeVar = shapeVar,
shapeY = shapeY, colorVar = colorVar, colorY = listColorY)
if(export){
tree <- tree%>%visExport()
}
if(!is.null(labelComplete) | rules){
tree <- tree %>% sparkline::spk_add_deps()
}
tree
}
.visUpdateTree <- function(graph, updateShape = NULL, shapeVar = NULL, shapeY = NULL){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visFocus with visNetwork object. Only within shiny & using visNetworkProxy")
}
tree <- list()
tree$updateShape <- updateShape
tree$shapeVar <- shapeVar
tree$shapeY <- shapeY
data <- list(id = graph$id, tree = tree)
graph$session$sendCustomMessage("visShinyUpdateTree", data)
graph
}
#Legend regression tree gradient color, still in dev
# ' <div style= "background: red;
# background: -webkit-linear-gradient(colorMax,',',colorMin,');
# background: -o-linear-gradient(colorMax,',',colorMin,');
# background: -moz-linear-gradient(colorMax,',',colorMin,');
# background: linear-gradient(colorMax,',',colorMin,');">Test gradient color</div>'
# ,
.parent <- function(x) {
if (x[1] != 1) {
c(Recall(if (x %% 2 == 0L) x / 2 else (x - 1) / 2), x)
} else {
x
}
}
.vis_give_rules <- function (object)
{
frame <- object$frame
ruleNums <- as.numeric(row.names(frame))
is.leaf <- (frame$var == "<leaf>")
frame[!is.leaf, "order"] <- seq_along(which(!is.leaf))
TF <- as.numeric(row.names(frame))[-1]%%2==0
ret <- ifelse(TF,
as.numeric(row.names(frame))[-1]/2,
(as.numeric(row.names(frame))[-1] - 1)/2)
ordeR <- frame[as.character(ret),"order"]
ret <- ifelse(TF, paste0("L", ordeR), paste0("R", ordeR))
ret <- c("No", ret)
rpartNodesNames <- as.numeric(row.names(frame))
out <- ret
names(out) <- paste0("Node", rpartNodesNames)
return(out)
}
.rpart_lists <- function (object)
{
ff <- object$frame
n <- nrow(ff)
if (n == 1L)
return("root")
is.leaf <- (ff$var == "<leaf>")
whichrow <- !is.leaf
vnames <- ff$var[whichrow]
index <- cumsum(c(1, ff$ncompete + ff$nsurrogate + (!is.leaf)))
irow <- index[c(whichrow, FALSE)]
ncat <- object$splits[irow, 2L]
lsplit <- rsplit <- list()
if (any(ncat < 2L)) {
jrow <- irow[ncat < 2L]
cutpoint <- object$splits[jrow, 4L]
temp1 <- (ifelse(ncat < 0, "<", ">="))[ncat < 2L]
temp2 <- (ifelse(ncat < 0, ">=", "<"))[ncat < 2L]
lsplit[ncat < 2L] <- cutpoint
rsplit[ncat < 2L] <- cutpoint
}
if (any(ncat > 1L)) {
xlevels <- attr(object, "xlevels")
jrow <- seq_along(ncat)[ncat > 1L]
crow <- object$splits[irow[ncat > 1L], 4L]
cindex <- (match(vnames, names(xlevels)))[ncat > 1L]
lsplit[jrow] <- lapply(seq_along(jrow), function(i) xlevels[[cindex[i]]][object$csplit[crow[i],
] == 1L])
rsplit[jrow] <- lapply(seq_along(jrow), function(i) xlevels[[cindex[i]]][object$csplit[crow[i],
] == 3L])
}
lsplit <- lapply(seq_along(lsplit), function(i) structure(lsplit[[i]],
compare = ifelse(ncat[i] < 2L, ifelse(ncat[i] < 0, "<",
">="), "=")))
rsplit <- lapply(seq_along(lsplit), function(i) structure(rsplit[[i]],
compare = ifelse(ncat[i] < 2L, ifelse(ncat[i] < 0, ">=",
"<"), "=")))
names(lsplit) <- vnames
names(rsplit) <- vnames
results <- list(L = lsplit, R = rsplit)
return(results)
}
subsetRpart <- function(tree,data, node = 1L) {
wh <- sapply(as.integer(rownames(tree$frame)), .parent)
wh <- unique(unlist(wh[sapply(wh, function(x) node %in% x)]))
data[rownames(tree$frame)[tree$where] %in% wh[wh >= node], , drop = FALSE]
}
.generateVarColor <- function(colorVar, nodes_var, SortLabel){
if(is.null(colorVar)){
colorVar <- data.frame(variable = unique(nodes_var), color = grDevices::hcl(seq(0, 250, length = length(unique(nodes_var))), l = 80))
}else{
if("data.frame" %in% class(colorVar)){
unused_var <- setdiff(colorVar$variable, setdiff(SortLabel, "<leaf>"))
if(length(unused_var) > 0){
colorVar <- colorVar[-which(colorVar$variable %in% unused_var), ]
}
miss_var <- setdiff(setdiff(SortLabel, "<leaf>"), colorVar$variable)
if(length(miss_var) > 0){
tmp_color <- setdiff(grDevices::hcl(seq(0, 250, length = nrow(colorVar) + length(miss_var)), l = 80), colorVar$color)
miss_color <- data.frame(variable = miss_var,
color = tmp_color[1:length(unique(miss_var))])
colorVar <- rbind.data.frame(colorVar, miss_color)
}
}else if("character" %in% class(colorVar)){
colorVar <- data.frame(variable = setdiff(SortLabel, "<leaf>"),
color = rep(colorVar, length(SortLabel))[1:length(setdiff(SortLabel, "<leaf>"))])
}
}
colorVar
}
.generateYColor <- function(object, colorY, nodes_var, digits = 3, infoClass = NULL, probs = NULL){
if(!is.null(attributes(object)$ylevels)){
if(is.null(infoClass)){
infoClass <- attributes(object)$ylevels
}
if(is.null(probs)){
probaClass <- object$frame[,"yval2"]
nlevelsClass <- length(infoClass)
effectif <- data.frame(probaClass[,2:(nlevelsClass+1), drop = F])
probs <- data.frame(probaClass[,(nlevelsClass+2):(ncol(probaClass)-1), drop = F])
}
# Classification tree
vardecidedClust <- infoClass[apply(probs, 1, which.max)]
if(is.null(colorY)){
colorY <- data.frame(modality = unique(infoClass),
color = grDevices::hcl(seq(250, 360, length = length(unique(infoClass))), l = 60))
}else{
if("data.frame" %in% class(colorY)){
miss_y <- setdiff(infoClass, colorY$modality)
if(length(miss_y) > 0){
miss_color <- data.frame(modality = miss_y,
color = grDevices::hcl(seq(250, 360, length = length(unique(miss_y))), l = 60))
colorY <- rbind.data.frame(colorY, miss_color)
}
}else if("character" %in% class(colorY)){
colorY <- data.frame(modality = infoClass,
color = rep(colorY, length(infoClass))[1:length(infoClass)])
}
}
list(colorY = colorY, vardecidedClust = vardecidedClust)
} else {
# Regression tree
vardecidedClust <- round(object$frame$yval, digits)
# palette
if(length(row.names(object$frame)) > 1){
meanV <- object$frame$yval-min(object$frame$yval)
meanV <- meanV/max(meanV)
} else {
meanV <- 1
}
colRamp <- .creatColorRampY(colorY)
colorTerm <- grDevices::rgb(colRamp(meanV), maxColorValue=255)
if(is.null(colorY)){
colorY <- c("#E6E0F8", "#8904B1")
} else if(length(colorY) > 1){
colorY <- c(colorY[1],colorY[2])
} else {
colorY <- c(NA,colorY[1])
}
list(colRamp = colRamp, colorTerm = colorTerm, colorY = colorY, vardecidedClust = vardecidedClust)
}
}
.creatColorRampY <- function(colorY)
{
if(is.null(colorY))
{
colRamp <- grDevices::colorRamp(c("#E6E0F8", "#8904B1"))
}else{
if(length(colorY) > 1){
colRamp <- grDevices::colorRamp(c(colorY[1],colorY[2]))
} else {
colRamp <- grDevices::colorRamp(c(NA,colorY[1]))
}
}
colRamp
}
#' Run and edit a visTree, and get back in R
#'
#' Needed packages : shiny, rpart, colourpicker, shinyWidgets
#'
#' @param data \code{rpart or data.drame}
#' @param ... all arguments except \code{object} present in \link{visTreeModuleServer}
#'
#' @examples
#'
#' \dontrun{
#'
#' net <- visTreeEditor(data = iris)
#' net <- visTreeEditor(data = rpart(iris), main = "visTree Editor")
#' net <- visTreeEditor(data = rpart(iris), tooltip_data = iris,
#' main = "visTree Editor")
#' net
#'
#' }
#'
#' @export
#'
#' @importFrom utils packageVersion
#'
#' @seealso \link{visTree}, \link{visTreeModuleServer}, \link{visNetworkEditor}
#'
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
#'
visTreeEditor <- function(data, ...){
.ctrlPckTree()
if("rpart" %in% class(data)){
rpartParams <- FALSE
} else if("data.frame" %in% class(data)){
rpartParams <- TRUE
}
return(shiny::runApp(shiny::shinyApp(ui = shiny::fluidPage(
visTreeModuleUI(id = "visTreeEditor", rpartParams = rpartParams, visTreeParams = TRUE, quitButton = TRUE)),
server = function(input, output, session) {
shiny::callModule(visTreeModuleServer, id = "visTreeEditor", data = shiny::reactive(data), ...)
})))
}
.giveLabelsFromDfWhichInvisible <- function(df, popSpkl = NULL, minPop = NULL, maxPop = NULL, meanPop = NULL){
# df <- df[!is.na(df[,1]),, drop = FALSE]
clM <- colMeans(df, na.rm = TRUE)
if(!is.null(popSpkl)){
nm <- names(df)
re <- list()
for(i in nm){
re[[i]] <- paste0("<br>", popSpkl[[i]],' : On pop. (mean:<b>', round(meanPop[i],2),"</b>)","<br>",
.addSparkLineOnlyJs(df[,i], type = "box",
min = minPop[[i]], max = maxPop[[i]]),
" : On grp. (mean:<b>", round(clM[i], 2),"</b>)")
}
}
re <- unlist(re)
paste(paste("<br> <b>",names(clM), ": </b>", re, collapse = ""))
}
.giveLabelsFromDfChrInvisible <- function(df, popSpkl, namOrder){
nm <- names(df)
re <- list()
for(i in nm){
tbl <- table(df[,i, drop = FALSE])
tbl <- tbl[na.omit(match(namOrder[[i]], names(tbl)))]
if(length(tbl) > 1){
tbl <- data.frame(tbl)
} else {
tbl <- data.frame(Var1 = names(tbl), Freq = tbl)
}
newMod <- namOrder[[i]][!namOrder[[i]]%in%tbl$Var1]
if(length(newMod) > 0){
tbl <- rbind(tbl, data.frame(Var1 = newMod, Freq = 0))
}
namOrder
tbl$Var1 <- ifelse(nchar(as.character(tbl$Var1) ) > 9, paste0(substr(tbl$Var1, 1, 8), "..."), as.character(tbl$Var1))
re[[i]] <- paste0(.addSparkLineOnlyJs(tbl$Freq, type = "pie", labels = tbl$Var1), "On grp. (mode:<b>", tbl[which.max(tbl$Freq),]$Var1,"</b>)")
}
re <- unlist(re)
paste(paste("<br> <b>",names(re), ": </b><br>", popSpkl, "<br>", re, collapse = ""))
}
#' @importFrom grDevices boxplot.stats
.addSparkLineOnlyJs <- function(vect, min = NULL, max = NULL, type = "line", labels = NULL){
getboxplotValues <- function(x){
x <- x[!is.na(x)]
if(length(x) >= 1){
x_box <- boxplot.stats(x)
x_out_range <- ifelse(length(x_box$out)>=2, range(x_box$out),NA)
return(sort(c(x_box$stats, x_out_range)))
} else{
return(NA)
}
}
if(is.null(min)) min <- min(vect, na.rm = TRUE)
if(is.null(max)) max <- max(vect, na.rm = TRUE)
drun <- sample(LETTERS, 15, replace = TRUE)
drun <- paste0(drun, collapse = "")
if(!is.null(labels)){
tltp <- paste0((1:length(labels))-1, ": '", labels, "'", collapse = ",")
tltp <- paste0("
tooltipFormat: \'{{offset:offset}} ({{percent.1}}%)\', tooltipValueLookups: {
\'offset\': { ", tltp, "}}")
}else{
tltp <- NULL
}
if(type != "box"){
ttr <- paste0('
$(function() {
$(".inlinesparkline', drun,'").sparkline([',paste0(vect, collapse = ",") ,'], {
type: "',type , '", chartRangeMin: ', min,', chartRangeMax: ', max,'
, ', tltp, '
});
});
')
} else {
vect <- getboxplotValues(vect)
if(!isTRUE(all.equal(NA, vect))){
ttr <- paste0('
$(function() {
$(".inlinesparkline', drun,'").sparkline([',paste0(vect, collapse = ",") ,'], {
type: "',type , '", raw : true, chartRangeMin: ', min,', chartRangeMax: ', max,'
, ', tltp, '
});
});
')
} else {
ttr <- ""
}
}
paste0('<div class="inlinesparkline', drun,'" style="display: inline-block;"> </div>',
'<script type="text/javascript">',
ttr,
'</script>')
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visTree.R
|
#' Module shiny for visualize and customize a \code{rpart} tree
#'
#' Needed packages : shiny, rpart, colourpicker, shinyWidgets, sparkline
#'
#' @param id \code{character} id of module, linked to \link{visTreeModuleServer}
#' @param rpartParams \code{boolean}, add tabs for rpart parameters (in case of \code{data.frame} in input)
#' @param visTreeParams \code{boolean}, add tabs for visTree parameters. Default to TRUE. Force to TRUE if \code{rpartParams}
#' @param quitButton \code{boolean}, add a button to quit module and get back network in R ?
#'
#' @param input \code{list} shiny input
#' @param output \code{list}, shiny output
#' @param session \code{list}, shiny session
#' @param data \code{reactive}, a \code{data.frame} or a \code{rpart} result. Must be a reactive object
#' @param tooltip_data \code{reactive}, a \code{data.frame}. if \code{data} is a \code{rpart},
#' data.frame used to build tree in order to plot \code{sparkline}
#'
#' @inheritParams visTree
#'
#'
#' @examples
#' \dontrun{
#'
#' require(rpart)
#' # simple module editor on rpart
#' data <- iris
#' shiny::shinyApp(ui = shiny::fluidPage(
#' visTreeModuleUI(id = "id1", rpartParams = FALSE, visTreeParams = FALSE)),
#' server = function(input, output, session) {
#' shiny::callModule(visTreeModuleServer, "id1", data = shiny::reactive(rpart(data)))
#' })
#'
#' # full module editor on rpart + data.frame for sparkline
#' data <- iris
#' shiny::shinyApp(ui = shiny::fluidPage(
#' visTreeModuleUI(id = "id1", rpartParams = FALSE, visTreeParams = TRUE)),
#' server = function(input, output, session) {
#' shiny::callModule(visTreeModuleServer, "id1", data = shiny::reactive(rpart(data)),
#' tooltip_data = data)
#' })
#'
#' # module on data.frame
#' shiny::shinyApp(ui = shiny::fluidPage(visTreeModuleUI(id = "id1",
#' rpartParams = TRUE)),
#' server = function(input, output, session) {
#' shiny::callModule(visTreeModuleServer, "id1", data = shiny::reactive(data))
#' })
#'
#' # multiple modules
#' shiny::shinyApp(ui =
#' navbarPage("Menu",shiny::tabPanel(
#' "tt1",shiny::fluidPage(visTreeModuleUI(id = "id1",
#' rpartParams = TRUE,
#' visTreeParams = TRUE))
#' ),
#' shiny::tabPanel(
#' "tt2",shiny::fluidPage(visTreeModuleUI(id = "id2",
#' rpartParams = FALSE,
#' visTreeParams = FALSE)))
#' ),
#' server = function(input, output, session) {
#' shiny::callModule(visTreeModuleServer, "id1", data = shiny::reactive(iris))
#' shiny::callModule(visTreeModuleServer, "id2", data = shiny::reactive(rpart(iris)))
#' })
#' }
#'
#' @name visNetwork-treeModule
#'
#' @export
#'
#' @importFrom stats as.formula
#' @importFrom grDevices col2rgb
#'
#' @references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
#'
visTreeModuleServer <- function(input, output, session, data,
tooltip_data = NULL,
tooltipColumns = "",
main = "",
submain = "",
footer = "",
direction = "UD",
fallenLeaves = FALSE,
rules = TRUE,
simplifyRules = TRUE,
shapeVar = "dot",
shapeY = "square",
colorVar = NULL,
colorY = NULL,
colorEdges = "#8181F7",
nodesFontSize = 16,
edgesFontSize = 14,
edgesFontAlign = "horizontal",
legend = TRUE,
legendNodesSize = 22,
legendFontSize = 16,
legendWidth = 0.1,
legendNcol = 1,
legendPosition = "left",
nodesPopSize = FALSE,
minNodeSize = 15,
maxNodeSize = 30,
highlightNearest = list(enabled = TRUE,
degree = list(from = 50000, to = 0), hover = FALSE,
algorithm = "hierarchical"),
collapse = list(enabled = TRUE, fit = TRUE, resetHighlight = TRUE,
clusterOptions = list(fixed = TRUE, physics = FALSE)),
updateShape = TRUE,
tooltipDelay = 500,
digits = 3,
height = 650,
width = "100%",
export = TRUE) {
ns <- session$ns
# reactive controls
if (!shiny::is.reactive(tooltip_data)){
get_tooltip_data <- shiny::reactive({tooltip_data})
} else {
get_tooltip_data <- tooltip_data
}
if (!shiny::is.reactive(tooltipColumns)){
get_tooltipColumns <- shiny::reactive({tooltipColumns})
} else {
get_tooltipColumns <- tooltipColumns
}
if (!shiny::is.reactive(main)){
get_main <- shiny::reactive({main})
} else {
get_main <- main
}
if (!shiny::is.reactive(submain)){
get_submain <- shiny::reactive({submain})
} else {
get_submain <- submain
}
if (!shiny::is.reactive(footer)){
get_footer <- shiny::reactive({footer})
} else {
get_footer <- footer
}
if (!shiny::is.reactive(direction)){
get_direction <- shiny::reactive({direction})
} else {
get_direction <- direction
}
if (!shiny::is.reactive(fallenLeaves)){
get_fallenLeaves <- shiny::reactive({fallenLeaves})
} else {
get_fallenLeaves <- fallenLeaves
}
if (!shiny::is.reactive(rules)){
get_rules <- shiny::reactive({rules})
} else {
get_rules <- rules
}
if (!shiny::is.reactive(simplifyRules)){
get_simplifyRules <- shiny::reactive({simplifyRules})
} else {
get_simplifyRules <- simplifyRules
}
if (!shiny::is.reactive(shapeVar)){
get_shapeVar <- shiny::reactive({shapeVar})
} else {
get_shapeVar <- shapeVar
}
if (!shiny::is.reactive(shapeY)){
get_shapeY <- shiny::reactive({shapeY})
} else {
get_shapeY <- shapeY
}
if (!shiny::is.reactive(colorVar)){
get_colorVar <- shiny::reactive({colorVar})
} else {
get_colorVar <- colorVar
}
if (!shiny::is.reactive(colorY)){
get_colorY <- shiny::reactive({colorY})
} else {
get_colorY <- colorY
}
if (!shiny::is.reactive(colorEdges)){
get_colorEdges <- shiny::reactive({colorEdges})
} else {
get_colorEdges <- colorEdges
}
if (!shiny::is.reactive(nodesFontSize)){
get_nodesFontSize <- shiny::reactive({nodesFontSize})
} else {
get_nodesFontSize <- nodesFontSize
}
if (!shiny::is.reactive(edgesFontSize)){
get_edgesFontSize <- shiny::reactive({edgesFontSize})
} else {
get_edgesFontSize <- edgesFontSize
}
if (!shiny::is.reactive(edgesFontAlign)){
get_edgesFontAlign <- shiny::reactive({edgesFontAlign})
} else {
get_edgesFontAlign <- edgesFontAlign
}
if (!shiny::is.reactive(legend)){
get_legend <- shiny::reactive({legend})
} else {
get_legend <- legend
}
if (!shiny::is.reactive(legendNodesSize)){
get_legendNodesSize <- shiny::reactive({legendNodesSize})
} else {
get_legendNodesSize <- legendNodesSize
}
if (!shiny::is.reactive(legendFontSize)){
get_legendFontSize <- shiny::reactive({legendFontSize})
} else {
get_legendFontSize <- legendFontSize
}
if (!shiny::is.reactive(legendWidth)){
get_legendWidth <- shiny::reactive({legendWidth})
} else {
get_legendWidth <- legendWidth
}
if (!shiny::is.reactive(legendNcol)){
get_legendNcol <- shiny::reactive({legendNcol})
} else {
get_legendNcol <- legendNcol
}
if (!shiny::is.reactive(legendPosition)){
get_legendPosition <- shiny::reactive({legendPosition})
} else {
get_legendPosition <- legendPosition
}
if (!shiny::is.reactive(nodesPopSize)){
get_nodesPopSize <- shiny::reactive({nodesPopSize})
} else {
get_nodesPopSize <- nodesPopSize
}
if (!shiny::is.reactive(minNodeSize)){
get_minNodeSize <- shiny::reactive({minNodeSize})
} else {
get_minNodeSize <- minNodeSize
}
if (!shiny::is.reactive(maxNodeSize)){
get_maxNodeSize <- shiny::reactive({maxNodeSize})
} else {
get_maxNodeSize <- maxNodeSize
}
if (!shiny::is.reactive(highlightNearest)){
get_highlightNearest <- shiny::reactive({highlightNearest})
} else {
get_highlightNearest <- highlightNearest
}
if (!shiny::is.reactive(collapse)){
get_collapse <- shiny::reactive({collapse})
} else {
get_collapse <- collapse
}
if (!shiny::is.reactive(updateShape)){
get_updateShape <- shiny::reactive({updateShape})
} else {
get_updateShape <- updateShape
}
if (!shiny::is.reactive(tooltipDelay)){
get_tooltipDelay <- shiny::reactive({tooltipDelay})
} else {
get_tooltipDelay <- tooltipDelay
}
if (!shiny::is.reactive(digits)){
get_digits <- shiny::reactive({digits})
} else {
get_digits <- digits
}
if (!shiny::is.reactive(height)){
get_height <- shiny::reactive({height})
} else {
get_height <- height
}
if (!shiny::is.reactive(width)){
get_width <- shiny::reactive({width})
} else {
get_width <- width
}
if (!shiny::is.reactive(export)){
get_export <- shiny::reactive({export})
} else {
get_export <- export
}
# create input
output$input_legend <- shiny::renderUI({
legend <- get_legend()
shiny::isolate({
shiny::checkboxInput(ns("legend"), "Display legend", value = legend)
})
})
shiny::outputOptions(output, "input_legend", suspendWhenHidden = FALSE)
output$input_fallenLeaves <- shiny::renderUI({
fallenLeaves <- get_fallenLeaves()
shiny::isolate({
shiny::checkboxInput(ns("fallenLeaves"), "Fallen leaves", fallenLeaves)
})
})
shiny::outputOptions(output, "input_fallenLeaves", suspendWhenHidden = FALSE)
output$input_rules <- shiny::renderUI({
rules <- get_rules()
shiny::isolate({
shiny::checkboxInput(ns("rules"),"Display rules", value = rules)
})
})
shiny::outputOptions(output, "input_rules", suspendWhenHidden = FALSE)
output$input_updateShape <- shiny::renderUI({
updateShape <- get_updateShape()
shiny::isolate({
shiny::checkboxInput(ns("updateShape"), "Update shape", value = updateShape)
})
})
shiny::outputOptions(output, "input_updateShape", suspendWhenHidden = FALSE)
output$input_export <- shiny::renderUI({
export <- get_export()
shiny::isolate({
shiny::checkboxInput(ns("export"), "Export", value = export)
})
})
shiny::outputOptions(output, "input_export", suspendWhenHidden = FALSE)
output$input_height <- shiny::renderUI({
height <- get_height()
shiny::isolate({
shiny::numericInput(ns("height"), "Height :", value = height)
})
})
shiny::outputOptions(output, "input_height", suspendWhenHidden = FALSE)
output$input_digits <- shiny::renderUI({
digits <- get_digits()
shiny::isolate({
shiny::numericInput(ns("digits"), "Digits : ", value = digits, min = 0)
})
})
shiny::outputOptions(output, "input_digits", suspendWhenHidden = FALSE)
output$input_tooltipDelay <- shiny::renderUI({
tooltipDelay <- get_tooltipDelay()
shiny::isolate({
shiny::numericInput(ns("tooltipDelay"), "Tooltip delay :", value = tooltipDelay, min = 0, step = 100)
})
})
shiny::outputOptions(output, "input_tooltipDelay", suspendWhenHidden = FALSE)
output$input_legendWidth <- shiny::renderUI({
legendWidth <- get_legendWidth()
shiny::isolate({
shiny::numericInput(ns("legendWidth"), "Width :", value = legendWidth, min = 0, max = 0.5, step = 0.05)
})
})
shiny::outputOptions(output, "input_legendWidth", suspendWhenHidden = FALSE)
output$input_legendNcol <- shiny::renderUI({
legendNcol <- get_legendNcol()
shiny::isolate({
shiny::numericInput(ns("legendNcol"), "Number of columns :", value = legendNcol, min = 1, max = 50, step = 1)
})
})
shiny::outputOptions(output, "input_legendNcol", suspendWhenHidden = FALSE)
output$input_legendPosition <- shiny::renderUI({
legendPosition <- get_legendPosition()
shiny::isolate({
shiny::selectInput(ns("legendPosition"), "Position", choices = c("left", "right"), selected = legendPosition)
})
})
shiny::outputOptions(output, "input_legendPosition", suspendWhenHidden = FALSE)
output$input_shapeY <- shiny::renderUI({
shapeY <- get_shapeY()
shiny::isolate({
shiny::selectInput(ns("shapeY"), "shape Y", choices = c("diamond",
"dot",
"star",
"triangle",
"triangleDown",
"square",
"ellipse",
"circle",
"database",
"box",
"text"), selected = shapeY)
})
})
shiny::outputOptions(output, "input_shapeY", suspendWhenHidden = FALSE)
output$input_shapeX <- shiny::renderUI({
shapeVar <- get_shapeVar()
shiny::isolate({
shiny::selectInput(ns("shapeX"), "shape X", choices = c("diamond",
"dot",
"star",
"triangle",
"triangleDown",
"square",
"ellipse",
"circle",
"database",
"box",
"text"), selected = shapeVar)
})
})
shiny::outputOptions(output, "input_shapeX", suspendWhenHidden = FALSE)
output$input_nodesSize <- shiny::renderUI({
nodesSize <- (get_maxNodeSize() + get_minNodeSize()) / 2
shiny::isolate({
shiny::numericInput(ns("nodesSize"), "Nodes size", value = nodesSize, min = 1)
})
})
shiny::outputOptions(output, "input_nodesSize", suspendWhenHidden = FALSE)
output$input_maxNodeSize <- shiny::renderUI({
value = get_maxNodeSize()
shiny::isolate({
shiny::numericInput(ns("maxNodeSize"), "Max nodes size", value = value, min = 1)
})
})
shiny::outputOptions(output, "input_maxNodeSize", suspendWhenHidden = FALSE)
output$input_minNodeSize <- shiny::renderUI({
value = get_minNodeSize()
shiny::isolate({
shiny::numericInput(ns("minNodeSize"), "Min nodes size", value = value, min = 1)
})
})
shiny::outputOptions(output, "input_minNodeSize", suspendWhenHidden = FALSE)
output$input_legendNodesSize <- shiny::renderUI({
legendNodesSize <- get_legendNodesSize()
shiny::isolate({
shiny::numericInput(ns("legendNodesSize"), "Legend size", value = legendNodesSize, min = 1)
})
})
shiny::outputOptions(output, "input_legendNodesSize", suspendWhenHidden = FALSE)
output$input_nodesFontSize <- shiny::renderUI({
nodesFontSize <- get_nodesFontSize()
shiny::isolate({
shiny::numericInput(ns("nodesFontSize"), "Nodes font", value = nodesFontSize, min = 1)
})
})
shiny::outputOptions(output, "input_nodesFontSize", suspendWhenHidden = FALSE)
output$input_legendFontSize <- shiny::renderUI({
legendFontSize <- get_legendFontSize()
shiny::isolate({
shiny::numericInput(ns("legendFontSize"), "Legend font", value = legendFontSize, min = 1)
})
})
shiny::outputOptions(output, "input_legendFontSize", suspendWhenHidden = FALSE)
output$input_colorEdges <- shiny::renderUI({
colorEdges <- get_colorEdges()
shiny::isolate({
colourpicker::colourInput(ns("colorEdges"), "Edges color", value = colorEdges)
})
})
shiny::outputOptions(output, "input_colorEdges", suspendWhenHidden = FALSE)
output$input_edgesFontSize <- shiny::renderUI({
edgesFontSize <- get_edgesFontSize()
shiny::isolate({
shiny::numericInput(ns("edgesFontSize"), "Edges font", value = edgesFontSize, min = 1)
})
})
shiny::outputOptions(output, "input_edgesFontSize", suspendWhenHidden = FALSE)
output$input_edgesFontAlign <- shiny::renderUI({
edgesFontAlign <- get_edgesFontAlign()
shiny::isolate({
shiny::selectInput(ns("edgesFontAlign"), "Edges font align",
choices = c("horizontal", "top", "middle", "bottom"),
selected = edgesFontAlign)
})
})
shiny::outputOptions(output, "input_edgesFontAlign", suspendWhenHidden = FALSE)
output$input_direction <- shiny::renderUI({
direction <- get_direction()
shiny::isolate({
shiny::selectInput(ns("direction"), "Direction :",
choices = c("up-down" = "UD", "down-up" = "DU",
"left-right" = "LR", "right-left" = "RL"),
selected = direction)
})
})
shiny::outputOptions(output, "input_direction", suspendWhenHidden = FALSE)
output$input_edgesFontAlign <- shiny::renderUI({
edgesFontAlign <- get_edgesFontAlign()
shiny::isolate({
shiny::selectInput(ns("edgesFontAlign"), "Edges font align",
choices = c("horizontal", "top", "middle", "bottom"),
selected = edgesFontAlign)
})
})
shiny::outputOptions(output, "input_edgesFontAlign", suspendWhenHidden = FALSE)
output$input_highlight <- shiny::renderUI({
highlightNearest <- get_highlightNearest()
shiny::isolate({
nearest <- TRUE
hover <- FALSE
if(is.logical(highlightNearest)){
nearest <- highlightNearest
hover <- FALSE
} else {
if(!is.null(highlightNearest$enabled)){
nearest <- highlightNearest$enabled
}
if(!is.null(highlightNearest$hover)){
hover <- highlightNearest$hover
}
}
shiny::fluidRow(
shiny::column(12,
shinyWidgets::materialSwitch(ns("highlightNearest"), "highlight nearest", status = "info", value = nearest),
shinyWidgets::materialSwitch(ns("highlightHover"), "highlight hover", status = "info", value = hover)
)
)
})
})
shiny::outputOptions(output, "input_highlight", suspendWhenHidden = FALSE)
output$input_collapse <- shiny::renderUI({
collapse <- get_collapse()
shiny::isolate({
value <- TRUE
if(is.logical(collapse)){
value <- collapse
} else {
if(!is.null(collapse$enabled)){
value <- collapse$enabled
}
}
shinyWidgets::materialSwitch(ns("collapse"), "Collapse", status = "info", value = value)
})
})
shiny::outputOptions(output, "input_collapse", suspendWhenHidden = FALSE)
# update main
output$input_main <- shiny::renderUI({
main <- get_main()
shiny::isolate({
text <- ""
color <- "black"
size <- 20
if(any(c("character", "factor") %in% class(main))){
text <- main
} else {
if(is.list(main)){
if(!is.null(main$text)){
text <- main$text
}
if(!is.null(main$style)){
find_size <- gregexpr("(font-size:)[[:digit:]]*", main$style)
tmp_size <- as.numeric(gsub("font-size:", "", unlist(regmatches(main$style, find_size))))[1]
if(!is.na(size)){
size <- tmp_size
}
find_color <- gregexpr("(color:#)[[:alnum:]]*", main$style)
tmp_color <- gsub("color:", "", unlist(regmatches(main$style, find_color)))[1]
if(!is.na(color)){
color <- tmp_color
}
}
}
}
shiny::fluidRow(
shiny::column(4,
shiny::textInput(ns("main"), "Main :", text)
),
shiny::column(4,
colourpicker::colourInput(ns("colourMain"),
"Main color :", value = color)
),
shiny::column(4,
shiny::numericInput(ns("mainsize"), "Main size :",
value = size, min = 1)
)
)
})
})
shiny::outputOptions(output, "input_main", suspendWhenHidden = FALSE)
# update submain
output$input_submain <- shiny::renderUI({
submain <- get_submain()
shiny::isolate({
text <- ""
color <- "black"
size <- 12
if(any(c("character", "factor") %in% class(submain))){
text <- submain
} else {
if(is.list(submain)){
if(!is.null(submain$text)){
text <- submain$text
}
if(!is.null(submain$style)){
find_size <- gregexpr("(font-size:)[[:digit:]]*", submain$style)
tmp_size <- as.numeric(gsub("font-size:", "", unlist(regmatches(submain$style, find_size))))[1]
if(!is.na(size)){
size <- tmp_size
}
find_color <- gregexpr("(color:#)[[:alnum:]]*", submain$style)
tmp_color <- gsub("color:", "", unlist(regmatches(submain$style, find_color)))[1]
if(!is.na(color)){
color <- tmp_color
}
}
}
}
shiny::fluidRow(
shiny::column(4,
shiny::textInput(ns("submain"), "Submain :", text)
),
shiny::column(4,
colourpicker::colourInput(ns("colourSubMain"),
"Submain color :", value = color)
),
shiny::column(4,
shiny::numericInput(ns("Submainsize"), "Submain size :",
value = size, min = 1)
)
)
})
})
shiny::outputOptions(output, "input_submain", suspendWhenHidden = FALSE)
# update footer
output$input_footer <- shiny::renderUI({
footer <- get_footer()
shiny::isolate({
text <- ""
color <- "black"
size <- 12
if(any(c("character", "factor") %in% class(footer))){
text <- footer
} else {
if(is.list(footer)){
if(!is.null(footer$text)){
text <- footer$text
}
if(!is.null(footer$style)){
find_size <- gregexpr("(font-size:)[[:digit:]]*", footer$style)
tmp_size <- as.numeric(gsub("font-size:", "", unlist(regmatches(footer$style, find_size))))[1]
if(!is.na(size)){
size <- tmp_size
}
find_color <- gregexpr("(color:#)[[:alnum:]]*", footer$style)
tmp_color <- gsub("color:", "", unlist(regmatches(footer$style, find_color)))[1]
if(!is.na(color)){
color <- tmp_color
}
}
}
}
shiny::fluidRow(
shiny::column(4,
shiny::textInput(ns("footer"), "Footer :", text)
),
shiny::column(4,
colourpicker::colourInput(ns("colourFooterMain"),
"Footer color :", value = color)
),
shiny::column(4,
shiny::numericInput(ns("Footermainsize"), "Footer size :",
value = size, min = 1)
)
)
})
})
shiny::outputOptions(output, "input_footer", suspendWhenHidden = FALSE)
shiny::observe({
if("data.frame" %in% class(data())){
shiny::updateSelectInput(session, inputId = "y", choices = names(data()))
}
})
shiny::observe({
if("data.frame" %in% class(data())){
shiny::updateSelectInput(session, inputId = "x", choices = names(data())[names(data())!=input$y],
selected = names(data())[names(data())!=input$y])
}
})
shiny::observe({
if("data.frame" %in% class(data())){
choices = 1:ncol(data())
names(choices) = names(data())
selected = get_tooltipColumns()
if(isTRUE(all.equal(selected, ""))){
selected <- choices
}else if(class(selected) %in% c("character", "factor")){
selected <- which(selected %in% names(data()))
}
shiny::isolate({
shiny::updateSelectInput(session, inputId = "tooltipColumns",
choices = choices,
selected = selected)
})
} else if(!is.null(get_tooltip_data()) && "data.frame" %in% class(get_tooltip_data())){
choices = 1:ncol(get_tooltip_data())
names(choices) = names(get_tooltip_data())
selected = get_tooltipColumns()
if(class(selected) %in% c("character", "factor")){
selected <- which(selected %in% names(get_tooltip_data()))
}
if(isTRUE(all.equal(selected, ""))){
selected <- choices
}
shiny::isolate({
shiny::updateSelectInput(session, inputId = "tooltipColumns", choices = choices, selected = selected)
})
}
})
output$is_data_frame <- shiny::reactive({
"data.frame" %in% class(data()) || (!is.null(get_tooltip_data()) && "data.frame" %in% class(get_tooltip_data()))
})
shiny::outputOptions(output, "is_data_frame", suspendWhenHidden = FALSE)
# Get rpart from reactive data
rpart_tree <- shiny::reactive({
input$runTree
if("rpart" %in% class(data())){
data()
} else {
if(input$runTree > 0){
shiny::isolate({
if(length(input$x) > 0){
x_frm <- paste0("`", paste0(input$x, collapse = "` + `"), "`")
} else {
x_frm <- " . "
}
formule <- paste0("`", input$y, "` ~ ", x_frm) %>% as.formula()
rpart::rpart(formule, data = data(),
control = rpart::rpart.control(cp = input$complexity, minsplit = input$minsplit))
})
} else {
NULL
}
}
})
shiny::observe({
input$y
input$x
input$complexity
input$minsplit
shiny::updateCheckboxInput(session,"usecolornodes", value = FALSE )
shiny::updateCheckboxInput(session,"usecolorY", value = FALSE )
})
# data.frame with variables colors
infoColors <- shiny::reactiveValues(colorVar = NULL, colorY = NULL)
current_tree_params <- shiny::reactiveValues()
# Build tree (visTree)
treeBuild <- shiny::reactive({
res <- rpart_tree()
if(!is.null(res)){
shiny::isolate({
main <- get_main()
submain <- get_submain()
footer <- get_footer()
direction <- get_direction()
fallenLeaves <- get_fallenLeaves()
rules <- get_rules()
simplifyRules <- get_simplifyRules()
shapeVar <- get_shapeVar()
shapeY <- get_shapeY()
colorVar <- get_colorVar()
colorY <- get_colorY()
colorEdges <- get_colorEdges()
nodesFontSize <- get_nodesFontSize()
edgesFontSize <- get_edgesFontSize()
edgesFontAlign <- get_edgesFontAlign()
legend <- get_legend()
legendNodesSize <- get_legendNodesSize()
legendFontSize <- get_legendFontSize()
legendWidth <- get_legendWidth()
legendNcol <- get_legendNcol()
legendPosition <- get_legendPosition()
nodesPopSize <- get_nodesPopSize()
minNodeSize <- get_minNodeSize()
maxNodeSize <- get_maxNodeSize()
highlightNearest <- get_highlightNearest()
collapse <- get_collapse()
updateShape <- get_updateShape()
tooltipDelay <- get_tooltipDelay()
digits <- get_digits()
height <- get_height()
width <- get_width()
export <- get_export()
if("data.frame" %in% class(data())){
data <- data()
tooltipColumns <- get_tooltipColumns()
if(isTRUE(all.equal(tooltipColumns, ""))){
tooltipColumns <- 1:ncol(data)
}
} else {
if(!is.null(get_tooltip_data()) && "data.frame" %in% class(get_tooltip_data())){
data <- get_tooltip_data()
tooltipColumns <- get_tooltipColumns()
if(isTRUE(all.equal(tooltipColumns, ""))){
tooltipColumns <- 1:ncol(data)
}
} else {
data <- NULL
tooltipColumns <- NULL
}
}
if("runTree" %in% names(input)){
if(input$runTree > 0){
legend <- input$legend
rules <- input$rules
tooltipDelay <- input$tooltipDelay
updateShape <- input$updateShape
fallenLeaves <- input$fallenLeaves
digits <- input$digits
height <- input$height
nodesPopSize <- input$nodesPopSize
export <- input$export
colorVar <- updateColorVar()
tmp_colorY <- updateColorY()
if("class" %in% res$method & is.data.frame(tmp_colorY)){
colorY <- tmp_colorY
} else if("anova" %in% res$method & "character" %in% class(tmp_colorY)){
colorY <- tmp_colorY
}
main = build_main()
submain = build_submain()
footer = build_footer()
simplifyRules <- ifelse(is.null(input$simpRules), simplifyRules, input$simpRules)
legendWidth <- ifelse(is.null(input$legendWidth), legendWidth, input$legendWidth)
legendNcol <- ifelse(is.null(input$legendNcol), legendNcol, input$legendNcol)
legendNodesSize <- ifelse(is.null(input$legendNodesSize), legendNodesSize, input$legendNodesSize)
legendFontSize <- ifelse(is.null(input$legendFontSize), legendFontSize, input$legendFontSize)
legendPosition <- ifelse(is.null(input$legendPosition), legendPosition, input$legendPosition)
minNodeSize <- ifelse(is.null(input$minNodeSize), minNodeSize, input$minNodeSize)
maxNodeSize <- ifelse(is.null(input$maxNodeSize), maxNodeSize, input$maxNodeSize)
direction <- ifelse(is.null(input$direction), direction, input$direction)
shapeY <- ifelse(is.null(input$shapeY), shapeY, input$shapeY)
shapeVar <- ifelse(is.null(input$shapeX), shapeVar, input$shapeX)
edgesFontSize <- ifelse(is.null(input$edgesFontSize), edgesFontSize, input$edgesFontSize)
edgesFontAlign <- ifelse(is.null(input$edgesFontAlign), edgesFontAlign, input$edgesFontAlign)
nodesFontSize <- ifelse(is.null(input$nodesFontSize), nodesFontSize, input$nodesFontSize)
colorEdges <- ifelse(is.null(input$colorEdges), colorEdges, input$colorEdges)
if("data.frame" %in% class(data())){
data <- data()
if(is.null(input$tooltipColumns)){
tooltipColumns <- NULL
} else if(length(input$tooltipColumns) == 0){
tooltipColumns <- NULL
} else {
tooltipColumns <- as.numeric(input$tooltipColumns)
}
} else {
if(!is.null(get_tooltip_data()) && "data.frame" %in% class(get_tooltip_data())){
data <- get_tooltip_data()
if(is.null(input$tooltipColumns)){
tooltipColumns <- NULL
} else if(length(input$tooltipColumns) == 0){
tooltipColumns <- NULL
} else {
tooltipColumns <- as.numeric(input$tooltipColumns)
}
} else {
data <- NULL
tooltipColumns <- NULL
}
}
}
}
current_tree_params$rules = rules
current_tree_params$simplifyRules = simplifyRules
current_tree_params$legend = legend
current_tree_params$legendWidth = legendWidth
current_tree_params$legendPosition = legendPosition
current_tree_params$legendNcol = legendNcol
current_tree_params$tooltipDelay = tooltipDelay
current_tree_params$digits = digits
current_tree_params$fallenLeaves = fallenLeaves
current_tree_params$updateShape = updateShape
current_tree_params$export = export
current_tree_params$data = data
current_tree_params$tooltipColumns = tooltipColumns
tree <- visTree(object = res,
data = data,
tooltipColumns = tooltipColumns,
main = main,
submain = submain,
footer = footer,
shapeY = shapeY,
shapeVar = shapeVar,
colorVar = colorVar,
colorY = colorY,
rules = rules,
simplifyRules = simplifyRules,
legend = legend,
legendWidth = legendWidth,
legendNodesSize = legendNodesSize,
legendFontSize = legendFontSize,
legendPosition = legendPosition,
legendNcol = legendNcol,
edgesFontSize = edgesFontSize,
edgesFontAlign = edgesFontAlign,
nodesFontSize = nodesFontSize,
nodesPopSize = nodesPopSize,
minNodeSize = minNodeSize,
maxNodeSize = maxNodeSize,
tooltipDelay = tooltipDelay,
digits = digits,
direction = direction,
fallenLeaves = fallenLeaves,
updateShape = updateShape,
colorEdges = colorEdges,
highlightNearest = highlightNearest,
collapse = collapse,
height = paste0(height, "px"),
export = export) %>%
visEvents(type = "on", doubleClick = "networkOpenCluster")
# save color information
infoColors$colorVar <- tree$x$tree$colorVar
infoColors$colorY <- tree$x$tree$colorY
tree
})
} else {
NULL
}
})
output$is_tree <- shiny::reactive({
!is.null(treeBuild())
})
shiny::outputOptions(output, "is_tree", suspendWhenHidden = FALSE)
# the tree
output$tree <- visNetwork::renderVisNetwork({
treeBuild()
})
# Give names of variables
infoRpartNodes <- shiny::reactive({
res <- rpart_tree()
if(!is.null(res)){
nodes_var <- as.character(res$frame$var)
nodes_var_x <- nodes_var[nodes_var != "<leaf>"]
sortLabels <- unique(nodes_var_x)
if(!is.null(attributes(res)$ylevels)){
infoClass <- attributes(res)$ylevels
nlevelsClass <- length(infoClass)
probaClass <- res$frame[,"yval2"]
effectif <- data.frame(probaClass[,2:(nlevelsClass+1), drop = F])
probs <- data.frame(probaClass[,(nlevelsClass+2):(ncol(probaClass)-1), drop = F])
} else {
infoClass <- NULL
probs <- NULL
}
list(nodes_var = nodes_var, nodes_var_x = nodes_var_x, sortLabels = sortLabels,
infoClass = infoClass, probs = probs)
}
})
# Get color
updateColorVar <- shiny::reactive({
newColorVar <- infoColors$colorVar
if(!is.null(newColorVar)){
input_name <- gsub(" ", "", paste0(newColorVar$variable, "var"))
newColorVar$color <- as.character(newColorVar$color)
if(!is.null(input[[input_name[1]]])){
colorVect <- sapply(input_name, function(X){
tmp <- input[[X]]
ifelse(is.null(tmp), "", tmp)
})
newColorVar$color[colorVect != ""] <- colorVect[colorVect != ""]
}
newColorVar
} else {
NULL
}
})
# Color for Y
updateColorY <- shiny::reactive({
colorY <- infoColors$colorY$colorY
if(is.data.frame(colorY)){
dest <- paste0(gsub(" ", "", paste0(colorY$modality, "Y")))
if(!is.null(input[[dest[1]]])){
colorVect <- sapply(dest, function(X)input[[X]])
colorY$color <- colorVect
}
}else{
if(!is.null(input$minY)){
colorY[1] <- input$minY
colorY[2] <- input$maxY
}
}
colorY
})
output$colornodes <- shiny::renderUI({
if(!input$usecolornodes){
return(NULL)
}else{
corNodes <- updateColorVar()
if(nrow(corNodes) > 0){
res <- apply(corNodes, 1, function(x){
as.character(shiny::column(6,colourpicker::colourInput(ns(gsub(" ", "", paste0(x[1],"var"))), paste0(x[1]," :"), x[2])))
}) %>% paste0(collapse = "") %>% htmltools::HTML()
}
}
})
# UI for color
output$colorY <- shiny::renderUI({
if(!input$usecolorY){
return(NULL)
}else{
corY <- updateColorY()
clas <- attributes(rpart_tree())$ylevels
if(!is.null(clas)){
res <- apply(corY, 1, function(x){
as.character(shiny::column(6,colourpicker::colourInput(ns(gsub(" ", "", paste0(x[1],"Y"))), paste0(x[1]," :"), x[2])))
})%>%
paste0(collapse = "") %>%
HTML()
}else{
res <- list()
res[[1]] <- as.character(shiny::column(6,
colourpicker::colourInput(ns("minY"), "Min y : ", corY[1])))
res[[2]] <- as.character(shiny::column(6,
colourpicker::colourInput(ns("maxY"), "Max y : ", corY[2])))
res <- paste0(res, collapse = "") %>%
HTML()
}
}
res
})
# Update color VarNodes
shiny::observe({
m <- treeBuild()
if(!is.null(m)){
oldId <- m$x$nodes$id
colorIn <- m$x$nodes$color
legOldId <- m$x$legend$nodes$id
legColorIn <- m$x$legend$nodes$color
outColor <- unlist(sapply(m$x$nodes$label, function(x){
if(is.null(input[[gsub(" ", "", paste0(x[1],"var"))]])){
"NoChange"
}else{
input[[gsub(" ", "", paste0(x[1],"var"))]]
}
}))
legOutColor <- unlist(sapply(m$x$legend$nodes$label, function(x){
if(is.null(input[[gsub(" ", "", paste0(x[1], "var"))]])){
"NoChange"
}else{
input[[gsub(" ", "", paste0(x[1], "var"))]]
}
}))
newColor <- data.frame(
id = oldId[outColor != "NoChange" & ifelse(outColor == colorIn, FALSE, TRUE)],
color = outColor[outColor != "NoChange" & ifelse(outColor == colorIn, FALSE, TRUE)]
)
legNewColor <- data.frame(
id = legOldId[legOutColor != "NoChange" & ifelse(legOutColor == legColorIn, FALSE, TRUE)],
color = legOutColor[legOutColor != "NoChange" & ifelse(legOutColor == legColorIn, FALSE, TRUE)]
)
clas <- attributes(shiny::isolate(rpart_tree()))$ylevels
if(!is.null(input$minY) & is.null(clas)){
coloramp <- .creatColorRampY(c(input$minY, input$maxY))
if(nrow(m$x$nodes) > 1){
meanV <- (m$x$nodes$labelClust-min(m$x$nodes$labelClust))/(max(m$x$nodes$labelClust-min(m$x$nodes$labelClust)))
} else {
meanV <- 1
}
colorTerm <- grDevices::rgb(coloramp(meanV), maxColorValue=255)
endf <- data.frame(id = m$x$nodes$id, colorClust = colorTerm, color = "")
endf$color <- as.character(endf$color)
endf$color[m$x$nodes$Leaf == 1] <- as.character(colorTerm[m$x$nodes$Leaf == 1])
endf$color[m$x$nodes$Leaf == 0] <- as.character(m$x$nodes$color[m$x$nodes$Leaf == 0])
visNetworkProxy(ns("tree")) %>%
visUpdateNodes(endf)
}
# if(!is.null(input[[gsub(" ", "", paste0(m$x$nodes[1,]$label, "Y"))]])){
oldId <- m$x$nodes$id
legId <- m$x$legend$nodes$id
colorIn <- m$x$nodes$color
colorInLeg <- as.character(m$x$legend$nodes$color)
outColor <- unlist(sapply(m$x$nodes$label, function(x){
if(is.null(input[[gsub(" ", "", paste0(x[1],"Y"))]])){
"NoChange"
}else{
input[[gsub(" ", "", paste0(x[1],"Y"))]]
}
}))
outColorLeg <- unlist(sapply(m$x$legend$nodes$label, function(x){
if(is.null(input[[gsub(" ", "", paste0(x[1],"Y"))]])){
"NoChange"
}else{
input[[gsub(" ", "", paste0(x[1],"Y"))]]
}
}))
newColorGraph <- data.frame(
id = oldId[outColor != "NoChange" & ifelse(outColor == colorIn, FALSE, TRUE)],
color = outColor[outColor != "NoChange" & ifelse(outColor == colorIn, FALSE, TRUE)]
)
newColorLegend <- data.frame(
id = legId[outColorLeg != "NoChange" & ifelse(outColorLeg == colorInLeg, FALSE, TRUE)],
color = outColorLeg[outColorLeg != "NoChange" & ifelse(outColorLeg == colorInLeg, FALSE, TRUE)]
)
# }
if(exists("newColor") & exists("newColorGraph")){
Gcol <- rbind(newColorGraph, newColor)
}else{
if(exists("newColor")){
Gcol <- newColor
}else{
if(exists("newColorGraph")){
Gcol <- newColorGraph
}
}
}
if(exists("legNewColor") & exists("newColorLegend")){
Lcol <- rbind(newColorLegend, legNewColor)
}else{
if(exists("legNewColor")){
Lcol <- legNewColor
}else{
if(exists("newColorLegend")){
Lcol <- newColorLegend
}
}
}
if(exists("Gcol")){
visNetworkProxy(ns("tree")) %>%
visUpdateNodes(Gcol) %>%
visUpdateNodes(Lcol, legend = TRUE)
}
}
})
# Update direction
shiny::observeEvent({!is.null(input$direction)}, {
# print("update direction")
visNetworkProxy(ns("tree")) %>%
visHierarchicalLayout(direction = input$direction)
}, ignoreNULL = TRUE, ignoreInit = TRUE)
# Update node size
shiny::observeEvent({
!is.null(input$minNodeSize) & !is.null(input$maxNodeSize) & input$nodesPopSize
}, {
# print("update nodes size")
minNodeSize <- input$minNodeSize
maxNodeSize <- input$maxNodeSize
m <- shiny::isolate(treeBuild())
if(input$nodesPopSize & !is.null(m)){
newNodes <- data.frame(id = m$x$nodes$id, scaling.min = minNodeSize, scaling.max = maxNodeSize)
visNetworkProxy(ns("tree")) %>%
visUpdateNodes(newNodes)
}
}, ignoreInit = TRUE)
# Update node size
shiny::observeEvent({!is.null(input$nodesSize) & input$nodesPopSize == FALSE}, {
nodesSize <- input$nodesSize
m <- shiny::isolate(treeBuild())
if(!input$nodesPopSize & !is.null(m)){
newNodes <- data.frame(id = m$x$nodes$id, scaling.min = nodesSize, scaling.max = nodesSize)
visNetworkProxy(ns("tree")) %>%
visUpdateNodes(newNodes)
}
}, ignoreInit = TRUE)
# Update legend node size
shiny::observeEvent(input$legendNodesSize, {
legendNodesSize <- input$legendNodesSize
m <- shiny::isolate(treeBuild())
if(!is.null(m$x$legend)){
change_legend_nodes <- data.frame(id = m$x$legend$nodes$id, size = legendNodesSize)
visNetworkProxy(ns("tree")) %>%
visUpdateNodes(change_legend_nodes, legend = TRUE)
}
}, ignoreInit = TRUE)
# Update legend font size
shiny::observeEvent(input$legendFontSize, {
legendFontSize <- input$legendFontSize
m <- shiny::isolate(treeBuild())
if(!is.null(m$x$legend)){
change_legend_nodes <- data.frame(id = m$x$legend$nodes$id, font.size = legendFontSize)
visNetworkProxy(ns("tree")) %>%
visUpdateNodes(change_legend_nodes, legend = TRUE)
}
}, ignoreInit = TRUE)
# Update edges color
shiny::observeEvent(input$colorEdges, {
colorEdges <- input$colorEdges
m <- shiny::isolate(treeBuild())
if(!is.null(m$x$edges)){
idEdges <- m$x$edges$id
newEdges <- data.frame(id = m$x$edges$id, color = colorEdges)
visNetworkProxy(ns("tree")) %>%
visUpdateEdges(newEdges)
}
}, ignoreInit = TRUE)
# Update edges font size
shiny::observeEvent(input$edgesFontSize, {
edgesFontSize <- input$edgesFontSize
m <- shiny::isolate(treeBuild())
if(!is.null(m$x$edges)){
idEdges <- m$x$edges$id
newEdges <- data.frame(id = m$x$edges$id, font.size = edgesFontSize)
visNetworkProxy(ns("tree")) %>%
visUpdateEdges(newEdges)
}
}, ignoreInit = TRUE)
# Update edges font align
shiny::observeEvent(input$edgesFontAlign, {
edgesFontAlign <- input$edgesFontAlign
m <- shiny::isolate(treeBuild())
if(!is.null(m$x$edges)){
idEdges <- m$x$edges$id
newEdges <- data.frame(id = m$x$edges$id, font.align = edgesFontAlign)
visNetworkProxy(ns("tree")) %>%
visUpdateEdges(newEdges)
}
}, ignoreInit = TRUE)
# Update nodes font size
shiny::observeEvent(input$nodesFontSize, {
nodesFontSize <- input$nodesFontSize
m <- shiny::isolate(treeBuild())
if(!is.null(m)){
newNodes <- data.frame(id = m$x$nodes$id, font.size = nodesFontSize)
visNetworkProxy(ns("tree")) %>%
visUpdateNodes(newNodes)
}
}, ignoreInit = TRUE)
# reactive for title
build_main <- shiny::reactive({
text <- input$main
style <- paste0("font-family:Georgia, Times New Roman, Times, serif;font-weight:bold;font-size:",
input$mainsize,"px;text-align:center;color:", input$colourMain, ";")
list(text = text, style = style)
})
# Update title
shiny::observeEvent({!is.null(input$main) & !is.null(input$mainsize) & !is.null(input$colourMain)}, {
# print("update main")
visNetworkProxy(ns("tree")) %>%
visSetTitle(main = build_main())
}, ignoreInit = TRUE)
build_submain <- shiny::reactive({
text <- input$submain
style <- paste0("font-family:Georgia, Times New Roman, Times, serif;font-size:",
input$Submainsize,"px;text-align:center;color:", input$colourSubMain, ";")
list(text = text, style = style)
})
shiny::observe({
visNetworkProxy(ns("tree")) %>%
visSetTitle(submain = build_submain())
})
build_footer <- shiny::reactive({
text <- input$footer
style <- paste0("font-family:Georgia, Times New Roman, Times, serif;font-size:",
input$Footermainsize,"px;text-align:center;color:", input$colourFooterMain, ";")
list(text = text, style = style)
})
shiny::observe({
visNetworkProxy(ns("tree")) %>%
visSetTitle(footer = build_footer())
})
# Update shape Ynodes
shiny::observeEvent({!is.null(input$shapeX) & !is.null(input$shapeY)},{
shapeX <- input$shapeX
shapeY <- input$shapeY
m <- shiny::isolate(treeBuild())
if(!is.null(m)){
# nodes
change_nodes <- data.frame(id = m$x$nodes$id, shape = ifelse(m$x$nodes$Leaf == 0, shapeX, shapeY))
visNetworkProxy(ns("tree")) %>%
visUpdateNodes(change_nodes) %>%
.visUpdateTree(shapeY = shapeY)
# legend
change_legend_nodes <- data.frame(id = m$x$legend$nodes$id, shape = ifelse(m$x$legend$nodes$Leaf == 0, shapeX, shapeY))
visNetworkProxy(ns("tree")) %>%
visUpdateNodes(change_legend_nodes, legend = TRUE)
}
}, ignoreInit = TRUE)
# Update highlightNearest
update_highlightNearest <- shiny::reactive({
list(enabled = input$highlightNearest, degree = list(from = 50000, to = 0),
hover = input$highlightHover, algorithm = "hierarchical")
})
shiny::observeEvent({!is.null(input$highlightNearest) & !is.null(input$highlightHover)}, {
visNetworkProxy(ns("tree")) %>%
visOptions(highlightNearest = list(enabled = input$highlightNearest, degree = list(from = 50000, to = 0),
hover = input$highlightHover, algorithm = "hierarchical"))
}, ignoreInit = TRUE)
# Update collapse
update_collapse <- shiny::reactive({
list(enabled = input$collapse, fit = TRUE, resetHighlight = TRUE,
clusterOptions = list(fixed = TRUE, physics= FALSE))
})
shiny::observeEvent({!is.null(input$collapse)}, {
visNetworkProxy(ns("tree")) %>%
visOptions(collapse = list(enabled = input$collapse, fit = TRUE, resetHighlight = TRUE,
clusterOptions = list(fixed = TRUE, physics= FALSE)))
}, ignoreInit = TRUE)
# Update height
output$treeUI <- shiny::renderUI({
res <- rpart_tree()
shiny::isolate({
height <- get_height()
if("runTree" %in% names(input)){
if(input$runTree > 0){
height <- ifelse(is.null(input$height), height, input$height)
}
}
visNetworkOutput(ns("tree"), height = paste0(height, "px"))
})
})
build_export_tree <- shiny::reactive({
res <- rpart_tree()
# legend <- ifelse(is.null(input$legend), get_legend(), input$legend)
# rules <- ifelse(is.null(input$rules), get_rules(), input$rules)
# tooltipDelay <- ifelse(is.null(input$tooltipDelay), get_tooltipDelay(), input$tooltipDelay)
# updateShape <- ifelse(is.null(input$updateShape), get_updateShape(), input$updateShape)
# fallenLeaves <- ifelse(is.null(input$fallenLeaves), get_fallenLeaves(), input$fallenLeaves)
# digits <- ifelse(is.null(input$digits), get_digits(), input$digits)
nodesPopSize <- ifelse(is.null(input$nodesPopSize), get_nodesPopSize(), input$nodesPopSize)
# export <- ifelse(is.null(input$export), get_export(), input$export)
# simplifyRules <- ifelse(is.null(input$simpRules), get_simplifyRules(), input$simpRules)
# legendWidth <- ifelse(is.null(input$legendWidth), get_legendWidth(), input$legendWidth)
# legendNcol <- ifelse(is.null(input$legendNcol), get_legendNcol(), input$legendNcol)
legendNodesSize <- ifelse(is.null(input$legendNodesSize), get_legendNodesSize(), input$legendNodesSize)
legendFontSize <- ifelse(is.null(input$legendFontSize), get_legendFontSize(), input$legendFontSize)
# legendPosition <- ifelse(is.null(input$legendPosition), get_legendPosition(), input$legendPosition)
minNodeSize <- ifelse(is.null(input$minNodeSize), get_minNodeSize(), input$minNodeSize)
maxNodeSize <- ifelse(is.null(input$maxNodeSize), get_maxNodeSize(), input$maxNodeSize)
direction <- ifelse(is.null(input$direction), get_direction(), input$direction)
shapeY <- ifelse(is.null(input$shapeY), get_shapeY(), input$shapeY)
shapeVar <- ifelse(is.null(input$shapeX), get_shapeVar(), input$shapeX)
edgesFontSize <- ifelse(is.null(input$edgesFontSize), get_edgesFontSize(), input$edgesFontSize)
edgesFontAlign <- ifelse(is.null(input$edgesFontAlign), get_edgesFontAlign(), input$edgesFontAlign)
nodesFontSize <- ifelse(is.null(input$nodesFontSize), get_nodesFontSize(), input$nodesFontSize)
colorEdges <- ifelse(is.null(input$colorEdges), get_colorEdges(), input$colorEdges)
colorVar <- updateColorVar()
colorY <- updateColorY()
rules <- current_tree_params$rules
simplifyRules <- current_tree_params$simplifyRules
legend <- current_tree_params$legend
legendWidth <- current_tree_params$legendWidth
legendPosition <- current_tree_params$legendPosition
legendNcol <- current_tree_params$legendNcol
tooltipDelay <- current_tree_params$tooltipDelay
digits <- current_tree_params$digits
fallenLeaves <- current_tree_params$fallenLeaves
updateShape <- current_tree_params$updateShape
export <- current_tree_params$export
data <- current_tree_params$data
tooltipColumns <- current_tree_params$tooltipColumns
out <- visTree(object = res,
data = data,
tooltipColumns = tooltipColumns,
main = build_main(),
submain = build_submain(),
footer = build_footer(),
shapeY = shapeY,
shapeVar = shapeVar,
colorVar = colorVar,
colorY = colorY,
rules = rules,
simplifyRules = simplifyRules,
legend = legend,
legendWidth = legendWidth,
legendNodesSize = legendNodesSize,
legendFontSize = legendFontSize,
legendPosition = legendPosition,
legendNcol = legendNcol,
edgesFontSize = edgesFontSize,
edgesFontAlign = edgesFontAlign,
nodesFontSize = nodesFontSize,
nodesPopSize = nodesPopSize,
minNodeSize = minNodeSize,
maxNodeSize = maxNodeSize,
tooltipDelay = tooltipDelay,
digits = digits,
direction = direction,
fallenLeaves = fallenLeaves,
updateShape = updateShape,
colorEdges = colorEdges,
highlightNearest = update_highlightNearest(),
collapse = update_collapse(),
height = paste0(input$export_height, "px"),
export = export)
})
# complexity update
cp_parameters <- shiny::reactiveValues(min = 0, max = 0.2, step = 0.001)
shiny::observeEvent(input$set_cp, {
shiny::showModal(shiny::modalDialog(
title = "Complexity parameters",
shiny::numericInput(ns("cp_min"), "Slider minimum :", shiny::isolate(cp_parameters$min), step = 0.1),
shiny::numericInput(ns("cp_max"), "Slider maximum :", shiny::isolate(cp_parameters$max), step = 0.1),
shiny::numericInput(ns("cp_step"), "Slider step :", shiny::isolate(cp_parameters$step), step = 0.001),
shiny::div(shiny::actionButton(ns("update_cp"), "Update complexity slider"), align = "center"),
easyClose = TRUE,
footer = NULL
))
})
shiny::observeEvent(input$update_cp, {
cp_parameters$min <- input$cp_min
cp_parameters$max <- input$cp_max
cp_parameters$step <- input$cp_step
shiny::updateSliderInput(session, "complexity", min = input$cp_min, max = input$cp_max, step = input$cp_step)
shiny::removeModal()
})
# download tree
output$downloadNetwork <- shiny::downloadHandler(
filename = function() {
paste('tree-', Sys.Date(), '.html', sep='')
},
content = function(con) {
out <- build_export_tree()
background <- input$export_background
#Transform color
if (grepl("^#", background, perl = TRUE)) {
bgcol <- col2rgb(background, alpha = TRUE)
background <- sprintf("rgba(%d,%d,%d,%f)", bgcol[1,1], bgcol[2,1], bgcol[3,1], bgcol[4,1]/255)
}
out %>% visSave(con, TRUE, background)
}
)
# quit and get back network
shiny::observe({
if(!is.null(input$quit_btn)){
if(input$quit_btn > 0){
shiny::stopApp(build_export_tree())
}
}
})
}
#' @rdname visNetwork-treeModule
#'
#' @export
visTreeModuleUI <- function(id, rpartParams = TRUE, visTreeParams = TRUE, quitButton = FALSE) {
ns <- shiny::NS(id)
.ctrlPckTree()
if(rpartParams){
visTreeParams <- TRUE
}
selectedTabs <- ifelse(rpartParams, "rpart", "visTree options")
shiny::fluidPage(
if(visTreeParams | rpartParams){
shiny::tabsetPanel(
id = ns('boxparam'),
selected = selectedTabs ,
if(rpartParams){
shiny::tabPanel("rpart",
#Params for rparts
shiny::fluidRow(
shiny::div(align = "center",
shiny::column(2,
shiny::selectInput(ns("y"), "Y :",NULL)
),
shiny::column(5,
shiny::selectInput(ns("x"), "X :", NULL, multiple = TRUE, selected = NULL, width = "100%")
),
shiny::column(2,
shiny::numericInput(ns("minsplit"), "Minsplit : ", value = 20, min = 2)
),
shiny::column(2,
shiny::sliderInput(ns("complexity"), "Complexity (cp) :",
min = 0, max = 0.2, value = 0.005, step = 0.001)
),
shiny::column(1,
shiny::br(), shiny::br(), shiny::actionButton(ns("set_cp"), "Set cp slider")
)
)
)
)
}else{shiny::div(style = "visibility: hidden")},
if(visTreeParams){
shiny::tabPanel("visTree options",
#Params graph
shiny::fluidRow(
shiny::column(1,
shiny::uiOutput(ns("input_height"))
),
shiny::column(1,
shiny::uiOutput(ns("input_digits"))
),
shiny::column(1,
shiny::uiOutput(ns("input_tooltipDelay"))
),
shiny::column(2,
shiny::br(), shiny::uiOutput(ns("input_fallenLeaves"))
),
shiny::column(2,
shiny::br(),
shiny::uiOutput(ns("input_updateShape"))
),
shiny::column(2,
shiny::br(),
shiny::uiOutput(ns("input_rules"))
),
shiny::conditionalPanel(paste0("input['",ns("rules"),"'] == true"),
shiny::column(2,
shiny::br(),
shiny::checkboxInput(ns("simpRules"),"Simplify rules", value = TRUE))
),
shiny::column(1,
shiny::br(),
shiny::uiOutput(ns("input_export"))
)
),
shiny::conditionalPanel(paste0("output['",ns("is_data_frame"),"'] === true"),
shiny::fluidRow(
shiny::column(12,
shiny::selectInput(ns("tooltipColumns"), "tooltipColumns :", NULL, multiple = TRUE, selected = NULL, width = "100%")
)
)
)
)
}else{shiny::div(style = "visibility: hidden")},
if(visTreeParams){
shiny::tabPanel("Legend",
shiny::fluidRow(
shiny::column(2, offset = 1,
shiny::br(),
shiny::uiOutput(ns("input_legend"))
),
# shiny::conditionalPanel(paste0("input['",ns("legend"),"'] == true"),
shiny::column(2,
shiny::uiOutput(ns("input_legendWidth"))
),
shiny::column(2,
shiny::uiOutput(ns("input_legendNcol"))
),
shiny::column(2,
shiny::uiOutput(ns("input_legendPosition"))
)
)
)
}else{shiny::div(style = "visibility: hidden")}
)
},
if(visTreeParams | rpartParams){
if(quitButton){
shiny::fluidRow(
shiny::column(width = 3, offset = 3,
shiny::div(
shiny::actionButton(ns("runTree"), "Run / update tree", class = "btnruntree"), align = "center"
)
),
shiny::column(width = 3,
shiny::div(
shiny::actionButton(ns("quit_btn"), "Quit and get back network in R"), align = "center"
)
)
)
} else {
shiny::div(
shiny::actionButton(ns("runTree"), "Run / update tree", class = "btnruntree"), align = "center"
)
}
}else{shiny::div(style = "visibility: hidden")},
shiny::hr(),
shiny::conditionalPanel(condition = paste0("output['", ns("is_tree"), "'] === true"),
shiny::fluidRow(
shiny::column(1,
shinyWidgets::dropdownButton(icon = shiny::icon("share-alt"),status = "danger",width = 500, circle = T,
label = "Update nodes properties", tooltip = TRUE,
shiny::fluidRow(
shiny::column(4,
shiny::uiOutput(ns("input_shapeY")),
shiny::uiOutput(ns("input_shapeX"))
),
shiny::column(4,
shiny::uiOutput(ns("input_nodesSize")),
shiny::uiOutput(ns("input_legendNodesSize"))
),
shiny::column(4,
shiny::uiOutput(ns("input_nodesFontSize")),
shiny::uiOutput(ns("input_legendFontSize"))
)
),
shiny::column(12,
shiny::br(),
shinyWidgets::materialSwitch(ns("nodesPopSize"),
"Nodes size use population", status = "info"),
shiny::conditionalPanel(paste0("input['", ns("nodesPopSize"),"'] == true"),
shiny::column(6,
shiny::uiOutput(ns("input_minNodeSize"))
),
shiny::column(6,
shiny::uiOutput(ns("input_maxNodeSize"))
)
),
shiny::br(),
shinyWidgets::materialSwitch(ns("usecolornodes"),"Color nodes", status = "info"),
shiny::fluidRow(
shiny::uiOutput(ns("colornodes"))
),
shiny::br(),
shinyWidgets::materialSwitch(ns("usecolorY"),"Color Y", status = "info"),
shiny::uiOutput(ns("colorY"))
)
)
),
shiny::column(1,
shinyWidgets::dropdownButton(icon = shiny::icon("exchange"), status = "warning", width = 300, circle = T,
label = "Update edges properties", tooltip = TRUE,
shiny::fluidRow(
shiny::column(12,
shiny::uiOutput(ns("input_colorEdges")),
shiny::uiOutput(ns("input_edgesFontSize")),
shiny::uiOutput(ns("input_edgesFontAlign"))
)
)
)
),
shiny::column(1,
shinyWidgets::dropdownButton(icon = shiny::icon("header"), status = "info", width = 400, circle = T,
label = "Set title, subtitle and footer", tooltip = TRUE,
shiny::fluidRow(
shiny::column(12,
shiny::uiOutput(ns("input_main")),
shiny::uiOutput(ns("input_submain")),
shiny::uiOutput(ns("input_footer"))
)
)
)
),
shiny::column(1,
shinyWidgets::dropdownButton(icon = shiny::icon("gear"),status = "success",width = 300,circle = T,
label = "Interaction and layout", tooltip = TRUE,
shiny:: fluidRow(
shiny::column(12,
shiny::uiOutput(ns("input_highlight")),
shiny::uiOutput(ns("input_collapse")),
shiny::uiOutput(ns("input_direction"))
)
)
)
),
shiny::column(1,
shinyWidgets::dropdownButton(icon = shiny::icon("download"),status = "default", width = 300, circle = T,
label = "Download the network as html", tooltip = TRUE,
shiny:: fluidRow(
shiny::column(12,
shiny::sliderInput(ns("export_height"), "Height:",
min = 200, max = 1400, value = 900),
# shinyWidgets::materialSwitch(ns("export_self"),
# "selfcontained ?", status = "info", value = TRUE),
colourpicker::colourInput(ns("export_background"),
"Background color :", value = "white"),
shiny::downloadLink(ns('downloadNetwork'), 'Download Tree as html')
)
)
)
)
),
shiny::uiOutput(ns("treeUI"))
)
)
}
.ctrlPckTree <- function(){
miss_packages <- c()
if(!requireNamespace("shiny", quietly = TRUE)){
miss_packages <- c(miss_packages, "'shiny (>1.0.0)'")
}
if(!requireNamespace("colourpicker", quietly = TRUE)){
miss_packages <- c(miss_packages, "'colourpicker'")
}
if(!requireNamespace("shinyWidgets", quietly = TRUE)){
miss_packages <- c(miss_packages, "'shinyWidgets'")
}
if(!requireNamespace("rpart", quietly = TRUE)){
miss_packages <- c(miss_packages, "'rpart'")
}
if(!requireNamespace("sparkline", quietly = TRUE)){
miss_packages <- c(miss_packages, "'sparkline'")
}
if(length(miss_packages) == 1){
stop(miss_packages," package is needed for this visTreeModule / visTreeEditor", call. = FALSE)
} else if(length(miss_packages) > 1){
stop(paste(miss_packages, collapse = ", ")," packages are needed for visTreeModule / visTreeEditor", call. = FALSE)
}
invisible(NULL)
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visTreeModule.R
|
#' Network visualization unselectAll method
#'
#' For use unselectAll() method in a shiny app. For full documentation, have a look at \link{visDocumentation}.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visUnselectAll <- function(graph){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visUnselectAll with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id)
graph$session$sendCustomMessage("visShinyUnselectAll", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visUnselectAll.R
|
#' Function to update the information of edges, with shiny only.
#'
#' Function to update the information of edges, with shiny only. You can also use this function passing new edges.
#' The link is based on id.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param edges : data.frame with the information of edges. See \link{visEdges}
#' \itemize{
#' \item{"id"}{ : edge id, for update}
#' \item{"from"}{ : node id, begin of the edge}
#' \item{"to"}{ : node id, end of the edge}
#' \item{"label"}{ : label}
#' \item{"value"}{ : size}
#' \item{"title"}{ : tooltip}
#' \item{...}{}
#'}
#'@param legend : Boolean. Update edges on legend ? Default to FALSE
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visUpdateEdges <- function(graph, edges, legend = FALSE){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visUpdateEdges with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, edges = edges, legend = legend)
graph$session$sendCustomMessage("visShinyUpdateEdges", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visUpdateEdges.R
|
#' Function to update the information of nodes, with shiny only.
#'
#' Function to update the information of nodes, with shiny only. You can also use this function passing new nodes.
#' The link is based on id.
#'
#'@param graph : a \code{\link{visNetworkProxy}} object
#'@param nodes : data.frame with the information of nodes. Needed at least column "id". See \link{visNodes}
#' \itemize{
#' \item{"id"}{ : id of the node, needed in the definition of edges and for update nodes}
#' \item{"label"}{ : label of the node}
#' \item{"group"}{ : group of the node. Groups can be configure with \link{visGroups}}
#' \item{"value"}{ : size of the node}
#' \item{"title"}{ : tooltip of the node}
#' \item{...}{}
#'}
#'@param updateOptions : Boolean. Update options (nodesIdSelection & selectedBy) if needed ? Default to TRUE.
#'@param legend : Boolean. Update nodes on legend ? Default to FALSE
#'
#'@seealso \link{visNodes} for nodes options, \link{visEdges} for edges options, \link{visGroups} for groups options,
#'\link{visLegend} for adding legend, \link{visOptions} for custom option, \link{visLayout} & \link{visHierarchicalLayout} for layout,
#'\link{visPhysics} for control physics, \link{visInteraction} for interaction, \link{visNetworkProxy} & \link{visFocus} & \link{visFit} for animation within shiny,
#'\link{visDocumentation}, \link{visEvents}, \link{visConfigure} ...
#'
#' @examples
#'\dontrun{
#'
#'# have a look to :
#'shiny::runApp(system.file("shiny", package = "visNetwork"))
#'
#'}
#'
#'@export
#'@references See online documentation \url{https://datastorm-open.github.io/visNetwork/}
visUpdateNodes <- function(graph, nodes, updateOptions = TRUE, legend = FALSE){
if(!any(class(graph) %in% "visNetwork_Proxy")){
stop("Can't use visUpdateNodes with visNetwork object. Only within shiny & using visNetworkProxy")
}
data <- list(id = graph$id, nodes = nodes, updateOptions = updateOptions, legend = legend)
graph$session$sendCustomMessage("visShinyUpdateNodes", data)
graph
}
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/R/visUpdateNodes.R
|
## -----------------------------------------------------------------------------
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges, width = "100%")
## ---- eval = FALSE------------------------------------------------------------
# # javascript api
# visDocumentation()
# vignette("Introduction-to-visNetwork") # with CRAN version
# # shiny examples
# shiny::runApp(system.file("shiny", package = "visNetwork"))
## -----------------------------------------------------------------------------
nodes <- data.frame(id = 1:10,
label = paste("Node", 1:10), # add labels on nodes
group = c("GrA", "GrB"), # add groups on nodes
value = 1:10, # size adding value
shape = c("square", "triangle", "box", "circle", "dot", "star",
"ellipse", "database", "text", "diamond"), # control shape of nodes
title = paste0("<p><b>", 1:10,"</b><br>Node !</p>"), # tooltip (html or character)
color = c("darkred", "grey", "orange", "darkblue", "purple"),# color
shadow = c(FALSE, TRUE, FALSE, TRUE, TRUE)) # shadow
head(nodes)
## -----------------------------------------------------------------------------
edges <- data.frame(from = sample(1:10, 8), to = sample(1:10, 8),
label = paste("Edge", 1:8), # add labels on edges
length = c(100,500), # length
arrows = c("to", "from", "middle", "middle;to"), # arrows
dashes = c(TRUE, FALSE), # dashes
title = paste("Edge", 1:8), # tooltip (html or character)
smooth = c(FALSE, TRUE), # smooth
shadow = c(FALSE, TRUE, FALSE, TRUE)) # shadow
head(edges)
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%")
## -----------------------------------------------------------------------------
nodes <- data.frame(id = 1:5, group = c(rep("A", 2), rep("B", 3)))
edges <- data.frame(from = c(2,5,3,3), to = c(1,2,4,2))
visNetwork(nodes, edges, width = "100%") %>%
visNodes(shape = "square") %>% # square for all nodes
visEdges(arrows ="to") %>% # arrow "to" for all edges
visGroups(groupname = "A", color = "darkblue") %>% # darkblue for group "A"
visGroups(groupname = "B", color = "red") # red for group "B"
## ---- echo=TRUE---------------------------------------------------------------
nb <- 10
nodes <- data.frame(id = 1:nb, label = paste("Label", 1:nb),
group = sample(LETTERS[1:3], nb, replace = TRUE), value = 1:nb,
title = paste0("<p>", 1:nb,"<br>Tooltip !</p>"), stringsAsFactors = FALSE)
edges <- data.frame(from = trunc(runif(nb)*(nb-1))+1,
to = trunc(runif(nb)*(nb-1))+1,
value = rnorm(nb, 10), label = paste("Edge", 1:nb),
title = paste0("<p>", 1:nb,"<br>Edge Tooltip !</p>"))
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%") %>% visLegend()
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%") %>%
visLegend(useGroups = FALSE, addNodes = data.frame(label = "Nodes", shape = "circle"),
addEdges = data.frame(label = "link", color = "black"))
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%") %>%
visOptions(highlightNearest = TRUE)
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%") %>%
visOptions(highlightNearest = list(enabled =TRUE, degree = 2))
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%") %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)
## -----------------------------------------------------------------------------
# can be the column you want
nodes$sel <- sample(c("sel1", "sel2"), nrow(nodes), replace = TRUE)
visNetwork(nodes, edges, width = "100%") %>%
visOptions(selectedBy = "sel")
## ---- echo = FALSE------------------------------------------------------------
nodes <- data.frame(id = 1:nb, label = paste("Label", 1:nb),
group = sample(1:nb, nb, replace = TRUE), value = 1:nb,
title = paste0("<p>", 1:nb,"<br>Tooltip !</p>"), stringsAsFactors = FALSE)
edges <- data.frame(from = trunc(runif(nb)*(nb-1))+1,
to = trunc(runif(nb)*(nb-1))+1,
title = paste0("<p>", 1:nb,"<br>Edge Tooltip !</p>"))
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%") %>%
visEdges(arrows = 'from')
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%") %>%
visInteraction(navigationButtons = TRUE)
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%") %>%
visOptions(manipulation = TRUE)
## ---- echo = TRUE-------------------------------------------------------------
nodes <- data.frame(id = 1:7)
edges <- data.frame(
from = c(1,2,2,2,3,3),
to = c(2,3,4,5,6,7)
)
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%") %>%
visEdges(arrows = "from") %>%
visHierarchicalLayout()
# same as visLayout(hierarchical = TRUE)
visNetwork(nodes, edges, width = "100%") %>%
visEdges(arrows = "from") %>%
visHierarchicalLayout(direction = "LR")
## -----------------------------------------------------------------------------
visNetwork(nodes, edges, width = "100%") %>%
visInteraction(dragNodes = FALSE, dragView = FALSE, zoomView = FALSE)
## ---- eval = FALSE------------------------------------------------------------
# # don't run here
# nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
# edges <- data.frame(from = c(1,2), to = c(2,3))
#
# visNetwork(nodes, edges, width = "100%") %>%
# visGroups(groupname = "A", shape = "icon", icon = list(code = "f0c0", size = 75)) %>%
# visGroups(groupname = "B", shape = "icon", icon = list(code = "f007", color = "red")) %>%
# visLegend() %>%
# addFontAwesome()
## ---- eval = T----------------------------------------------------------------
library(rpart)
# Complex tree
data("solder")
res <- rpart(Opening~., data = solder, control = rpart.control(cp = 0.00005))
visTree(res, height = "800px", nodesPopSize = TRUE, minNodeSize = 10, maxNodeSize = 30)
## ---- eval = FALSE------------------------------------------------------------
# output$mynetwork <- renderVisNetwork({... visOptions(nodesIdSelection = TRUE)}) # created input$mynetwork_selected
#
## ---- eval = FALSE------------------------------------------------------------
# network <- visNetwork(nodes, edges, width = "100%")
# visSave(network, file = "network.html")
## -----------------------------------------------------------------------------
visNetwork(dot = 'dinetwork {1 -> 1 -> 2; 2 -> 3; 2 -- 4; 2 -> 1 }', width = "100%")
## ---- eval = FALSE------------------------------------------------------------
# # don't run here
# visNetwork(gephi = 'WorldCup2014.json')
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/doc/Introduction-to-visNetwork.R
|
---
title: "Introduction to visNetwork"
author: "B. Thieurmel - DataStorm"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Introduction to visNetwork}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
**visNetwork** is a R package for network visualization, using **vis.js** javascript library (https://visjs.org). All the remarks and bugs returns are welcome on github : https://github.com/datastorm-open/visNetwork.
## Minimal example
**visNetwork** needs at least two informations :
* a nodes data.frame, with *id* column
* a edges data.frame, with *from* and *to* columns
```{r}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges, width = "100%")
```
## Find help
Besides the help R functions, a vignette is available, and you can access and read the full javascript API :
```{r, eval = FALSE}
# javascript api
visDocumentation()
vignette("Introduction-to-visNetwork") # with CRAN version
# shiny examples
shiny::runApp(system.file("shiny", package = "visNetwork"))
```
Or visit our online documentation : http://datastorm-open.github.io/visNetwork/.
## Simple individual nodes and edges customization
* Adding more variables on nodes data.frame. See **_visNodes_** for available options.
```{r}
nodes <- data.frame(id = 1:10,
label = paste("Node", 1:10), # add labels on nodes
group = c("GrA", "GrB"), # add groups on nodes
value = 1:10, # size adding value
shape = c("square", "triangle", "box", "circle", "dot", "star",
"ellipse", "database", "text", "diamond"), # control shape of nodes
title = paste0("<p><b>", 1:10,"</b><br>Node !</p>"), # tooltip (html or character)
color = c("darkred", "grey", "orange", "darkblue", "purple"),# color
shadow = c(FALSE, TRUE, FALSE, TRUE, TRUE)) # shadow
head(nodes)
```
* Adding more variables on edges data.frame. See **_visEdges_** for available options.
```{r}
edges <- data.frame(from = sample(1:10, 8), to = sample(1:10, 8),
label = paste("Edge", 1:8), # add labels on edges
length = c(100,500), # length
arrows = c("to", "from", "middle", "middle;to"), # arrows
dashes = c(TRUE, FALSE), # dashes
title = paste("Edge", 1:8), # tooltip (html or character)
smooth = c(FALSE, TRUE), # smooth
shadow = c(FALSE, TRUE, FALSE, TRUE)) # shadow
head(edges)
```
```{r}
visNetwork(nodes, edges, width = "100%")
```
## Global nodes/edges configuration
* Set global options for nodes and edges using **_visNodes_** and **_visEdges_**, and use options per group using **_visGroups_**.
```{r}
nodes <- data.frame(id = 1:5, group = c(rep("A", 2), rep("B", 3)))
edges <- data.frame(from = c(2,5,3,3), to = c(1,2,4,2))
visNetwork(nodes, edges, width = "100%") %>%
visNodes(shape = "square") %>% # square for all nodes
visEdges(arrows ="to") %>% # arrow "to" for all edges
visGroups(groupname = "A", color = "darkblue") %>% # darkblue for group "A"
visGroups(groupname = "B", color = "red") # red for group "B"
```
# Network configuration
Configuration options are available in *visOptions*, *visInteraction*, *visLayout*, *visHierarchicalLayout*, *visPhysics* :
## Example Data
```{r, echo=TRUE}
nb <- 10
nodes <- data.frame(id = 1:nb, label = paste("Label", 1:nb),
group = sample(LETTERS[1:3], nb, replace = TRUE), value = 1:nb,
title = paste0("<p>", 1:nb,"<br>Tooltip !</p>"), stringsAsFactors = FALSE)
edges <- data.frame(from = trunc(runif(nb)*(nb-1))+1,
to = trunc(runif(nb)*(nb-1))+1,
value = rnorm(nb, 10), label = paste("Edge", 1:nb),
title = paste0("<p>", 1:nb,"<br>Edge Tooltip !</p>"))
```
## Add legend
It's possible to add more custom legend on nodes / edges ! Default on groups (like in previous versions) :
```{r}
visNetwork(nodes, edges, width = "100%") %>% visLegend()
```
Or passing data :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visLegend(useGroups = FALSE, addNodes = data.frame(label = "Nodes", shape = "circle"),
addEdges = data.frame(label = "link", color = "black"))
```
## Highlight nearest
You can highlight nearest nodes and edges clicking on a node with **highlightNearest** option :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visOptions(highlightNearest = TRUE)
```
It's now possible to control the degree of depth (visNetwork >= 0.1.2) :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visOptions(highlightNearest = list(enabled =TRUE, degree = 2))
```
## Select by node id
You can also select nodes by id/label with a list with **nodesIdSelection** :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)
```
## Select by a column
And select some nodes by the values of a column using **selectedBy** option :
```{r}
# can be the column you want
nodes$sel <- sample(c("sel1", "sel2"), nrow(nodes), replace = TRUE)
visNetwork(nodes, edges, width = "100%") %>%
visOptions(selectedBy = "sel")
```
## Directed Network
```{r, echo = FALSE}
nodes <- data.frame(id = 1:nb, label = paste("Label", 1:nb),
group = sample(1:nb, nb, replace = TRUE), value = 1:nb,
title = paste0("<p>", 1:nb,"<br>Tooltip !</p>"), stringsAsFactors = FALSE)
edges <- data.frame(from = trunc(runif(nb)*(nb-1))+1,
to = trunc(runif(nb)*(nb-1))+1,
title = paste0("<p>", 1:nb,"<br>Edge Tooltip !</p>"))
```
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visEdges(arrows = 'from')
```
## Custom navigation
*vis.js* propose some navigation tools :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visInteraction(navigationButtons = TRUE)
```
## Data Manipulation
And some data manipulation tools :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visOptions(manipulation = TRUE)
```
## Hierarchical Layout
You can use and control hierarchical layout with *visHierarchicalLayout* and *visLayout* :
```{r, echo = TRUE}
nodes <- data.frame(id = 1:7)
edges <- data.frame(
from = c(1,2,2,2,3,3),
to = c(2,3,4,5,6,7)
)
```
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visEdges(arrows = "from") %>%
visHierarchicalLayout()
# same as visLayout(hierarchical = TRUE)
visNetwork(nodes, edges, width = "100%") %>%
visEdges(arrows = "from") %>%
visHierarchicalLayout(direction = "LR")
```
## Freeze network
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visInteraction(dragNodes = FALSE, dragView = FALSE, zoomView = FALSE)
```
# Additional features
## Use font awesome icons in your network
You can use **Font Awesome** icons using groups or nodes options. **Font Awesome** library (https://fontawesome.com/) is not part of default dependencies. use addFontAwesome() if needed.
```{r, eval = FALSE}
# don't run here
nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
edges <- data.frame(from = c(1,2), to = c(2,3))
visNetwork(nodes, edges, width = "100%") %>%
visGroups(groupname = "A", shape = "icon", icon = list(code = "f0c0", size = 75)) %>%
visGroups(groupname = "B", shape = "icon", icon = list(code = "f007", color = "red")) %>%
visLegend() %>%
addFontAwesome()
```
## Visualize rpart object
New *visTree* function allows to visualize and customize a *rpart* classification and regression tree. Have a look to *visTreeEditor* to edity and get back network, or to *visTreeModuleServer* to use custom tree module in R.
```{r, eval = T}
library(rpart)
# Complex tree
data("solder")
res <- rpart(Opening~., data = solder, control = rpart.control(cp = 0.00005))
visTree(res, height = "800px", nodesPopSize = TRUE, minNodeSize = 10, maxNodeSize = 30)
```
## Use in Shiny
With *visNetworkOutput* and *renderVisNetwork*. Using with shiny, and enabled options *nodesIdSelection*, you can access to new input with current selection value. Morevoer, you can do a lot of things with *visNetworkProxy*
```{r, eval = FALSE}
output$mynetwork <- renderVisNetwork({... visOptions(nodesIdSelection = TRUE)}) # created input$mynetwork_selected
```
And with *selectedBy*, new input __input$mynetwork_selectedBy__.
## Physics, tooltip, events,
You can also control :
* physics of network : *visPhysics*
* events : *visEvents*
## Export
```{r, eval = FALSE}
network <- visNetwork(nodes, edges, width = "100%")
visSave(network, file = "network.html")
```
## Use DOT language data
```{r}
visNetwork(dot = 'dinetwork {1 -> 1 -> 2; 2 -> 3; 2 -- 4; 2 -> 1 }', width = "100%")
```
## Use gephi json export file
```{r, eval = FALSE}
# don't run here
visNetwork(gephi = 'WorldCup2014.json')
```
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/doc/Introduction-to-visNetwork.Rmd
|
require(shiny)
require(visNetwork)
shinyServer(function(input, output) {
source("./src/server/basic_server.R", local = TRUE, encoding = "UTF-8")
source("./src/server/options_server.R", local = TRUE, encoding = "UTF-8")
source("./src/server/manip_server.R", local = TRUE, encoding = "UTF-8")
source("./src/server/proxy_nodes_server.R", local = TRUE, encoding = "UTF-8")
source("./src/server/proxy_anim_server.R", local = TRUE, encoding = "UTF-8")
source("./src/server/proxy_update_server.R", local = TRUE, encoding = "UTF-8")
source("./src/server/proxy_options_server.R", local = TRUE, encoding = "UTF-8")
source("./src/server/proxy_select_server.R", local = TRUE, encoding = "UTF-8")
source("./src/server/proxy_get_server.R", local = TRUE, encoding = "UTF-8")
source("./src/server/proxy_set_title_server.R", local = TRUE, encoding = "UTF-8")
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/server.R
|
output$network_hello <- renderVisNetwork({
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges)
})
output$code_network_hello <- renderText({
'
# in server.R :
output$network_hello <- renderVisNetwork({
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges)
})
# in ui.R
visNetworkOutput("network_hello",height = "200px")
'
})
output$network_icon <- renderVisNetwork({
nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
edges <- data.frame(from = c(1,2), to = c(2,3))
visNetwork(nodes, edges) %>%
visGroups(groupname = "A", shape = "icon", icon = list(code = "f0c0", size = 75)) %>%
visGroups(groupname = "B", shape = "icon", icon = list(code = "f007", color = "red")) %>%
addFontAwesome() %>%
visLegend(addNodes = data.frame(label = c("A", "B"), shape = "icon",
icon.code = c("f0c0", "f007"),
icon.size = c(25,50),
icon.color = c(NA, "red")),
addEdges = data.frame(label = "link"), useGroups = FALSE)
})
output$code_network_icon <- renderText({
'
nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
edges <- data.frame(from = c(1,2), to = c(2,3))
visNetwork(nodes, edges) %>%
visGroups(groupname = "A", shape = "icon", icon = list(code = "f0c0", size = 75)) %>%
visGroups(groupname = "B", shape = "icon", icon = list(code = "f007", color = "red")) %>%
addFontAwesome() %>%
visLegend(addNodes = data.frame(label = c("A", "B"), shape = "icon",
icon.code = c("f0c0", "f007"),
icon.size = c(25,50),
icon.color = c(NA, "red")),
addEdges = data.frame(label = "link"), useGroups = FALSE)
'
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/server/basic_server.R
|
output$network_manip <- renderVisNetwork({
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges) %>%
visOptions(manipulation = list(enabled = TRUE,
editEdgeCols = c("label"),
editNodeCols = c("group"),
addNodeCols = c("id", "label")))
})
output$view_manip <- renderPrint({
input$network_manip_graphChange
})
output$code_network_manip <- renderText({
'
visNetwork(nodes, edges)
visOptions(manipulation = list(enabled = TRUE,
editEdgeCols = c("label"),
editNodeCols = c("group"),
addNodeCols = c("id", "label")))
'
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/server/manip_server.R
|
output$network_id <- renderVisNetwork({
nodes <- data.frame(id = 1:15, label = paste("Label", 1:15),
group = sample(LETTERS[1:3], 15, replace = TRUE))
edges <- data.frame(from = trunc(runif(15)*(15-1))+1,
to = trunc(runif(15)*(15-1))+1)
# visNetwork(nodes, edges, main = "Title", submain = "Subtitle", footer = "footer") %>%
# visExport()
visNetwork(nodes, edges, main = "Title", submain = "Subtitle") %>%
visExport() %>%
visOptions(highlightNearest = TRUE,
nodesIdSelection = list(enabled = TRUE, selected = "1"))
visNetwork(nodes, edges) %>%
visConfigure(enabled = TRUE, filter = "interaction")
})
output$view_id <- renderText({
paste("Current node selection : ", input$network_id_selected)
})
output$code_network_id <- renderText({
'
visNetwork(nodes, edges, main = "Title", submain = "Subtitle") %>%
visExport() %>%
visOptions(highlightNearest = TRUE,
nodesIdSelection = list(enabled = TRUE, selected = "1"))
'
})
output$network_group <- renderVisNetwork({
nodes <- data.frame(id = 1:15, label = paste("Label", 1:15),
group = sample(LETTERS[1:3], 15, replace = TRUE))
edges <- data.frame(from = trunc(runif(15)*(15-1))+1,
to = trunc(runif(15)*(15-1))+1)
visNetwork(nodes, edges) %>%
visOptions(selectedBy = list(variable = "group", selected = "A"))
})
output$view_group <- renderText({
paste("Current variable selection : ", input$network_group_selectedBy)
})
output$code_network_group <- renderText({
'
visNetwork(nodes, edges) %>%
visOptions(selectedBy = list(variable = "group", selected = "A"))
'
})
output$view_highlight_color <- renderText({
paste("Highlighted nodes (color) : ", paste(input$network_id_highlight_color_id, collapse = ", "))
})
output$view_highlight_label <- renderText({
paste("Highlighted nodes (label only) : ", paste(input$network_id_highlight_label_id, collapse = ", "))
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/server/options_server.R
|
dataan <- reactive({
set.seed(2)
nodes <- data.frame(id = 1:15, label = paste("Label", 1:15),
group = sample(LETTERS[1:3], 15, replace = TRUE))
edges <- data.frame(from = trunc(runif(15)*(15-1))+1,
to = trunc(runif(15)*(15-1))+1)
list(nodes = nodes, edges = edges)
})
output$network_proxy_focus <- renderVisNetwork({
visNetwork(dataan()$nodes, dataan()$edges) %>% visLegend()
})
observe({
visNetworkProxy("network_proxy_focus") %>%
visFocus(id = input$Focus, scale = input$scale_id)
# visRemoveNodes(id = input$Focus)
# visFit(nodes = input$Focus)
})
observe({
gr <- input$Group
isolate({
if(gr != "ALL"){
nodes <- dataan()$nodes
id <- nodes$id[nodes$group%in%gr]
}else{
id <- NULL
}
visNetworkProxy("network_proxy_focus") %>%
visFit(nodes = id)
})
})
output$code_proxy_focus <- renderText({
'
observe({
visNetworkProxy("network_proxy_focus") %>%
visFocus(id = input$Focus, scale = input$scale_id)
})
observe({
gr <- input$Group
isolate({
if(gr != "ALL"){
nodes <- dataan()$nodes
id <- nodes$id[nodes$group%in%gr]
}else{
id <- NULL
}
visNetworkProxy("network_proxy_focus") %>%
visFit(nodes = id)
})
})
'
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/server/proxy_anim_server.R
|
dataget <- reactive({
set.seed(2)
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
list(nodes = nodes, edges = edges)
})
output$network_proxy_get <- renderVisNetwork({
visNetwork(dataget()$nodes, dataget()$edges) %>% visLegend()
})
observe({
input$getEdges
visNetworkProxy("network_proxy_get") %>%
visGetEdges()
})
observe({
input$getNodes
visNetworkProxy("network_proxy_get") %>%
visGetNodes()
})
output$edges_data_from_shiny <- renderPrint({
if(!is.null(input$network_proxy_get_edges)){
input$network_proxy_get_edges
}
})
output$nodes_data_from_shiny <- renderPrint({
if(!is.null(input$network_proxy_get_nodes)){
input$network_proxy_get_nodes
}
})
observe({
input$updateGet
nodes <- data.frame(id = 4, color = "red")
edges <- edges <- data.frame(id = "newedges", from = c(4), to = c(1))
visNetworkProxy("network_proxy_get") %>%
visUpdateNodes(nodes = nodes) %>%
visUpdateEdges(edges = edges)
})
output$code_proxy_get <- renderText({
'
observe({
input$getEdges
visNetworkProxy("network_proxy_get") %>%
visGetEdges()
})
observe({
input$getNodes
visNetworkProxy("network_proxy_get") %>%
visGetNodes()
})
output$edges_data_from_shiny <- renderPrint({
if(!is.null(input$network_proxy_get_edges)){
input$network_proxy_get_edges
}
})
output$nodes_data_from_shiny <- renderPrint({
if(!is.null(input$network_proxy_get_nodes)){
input$network_proxy_get_nodes
}
})
'
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/server/proxy_get_server.R
|
output$network_proxy_nodes <- renderVisNetwork({
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges)%>%
visNodes(color = "blue", size = 20)
})
observe({
visNetworkProxy("network_proxy_nodes") %>%
visNodes(color = input$color, size = input$size, shadow = input$shadow) %>%
visEdges(dashes = input$dashes, smooth = input$smooth)
})
# observe({
# visNetworkProxy("network_proxy_nodes") %>%
# visSetOptions(options = list(nodes = list(color = input$color, size = input$size, shadow = input$shadow),
# edges = list(dashes = input$dashes, smooth = input$smooth)))
# })
output$code_proxy_nodes <- renderText({
'
output$network_proxy_nodes <- renderVisNetwork({
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges)
})
observe({
visNetworkProxy("network_proxy_nodes") %>%
visNodes(color = input$color, size = input$size, shadow = input$shadow) %>%
visEdges(dashes = input$dashes, smooth = input$smooth)
})
# same directly with visSetOptions :
observe({
visNetworkProxy("network_proxy_nodes") %>%
visSetOptions(options = list(nodes = list(color = input$color, size = input$size, shadow = input$shadow),
edges = list(dashes = input$dashes, smooth = input$smooth)))
})
'
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/server/proxy_nodes_server.R
|
dataos <- reactive({
set.seed(2)
nodes <- data.frame(id = 1:15, label = paste("Label", 1:15),
group = sample(LETTERS[1:3], 15, replace = TRUE),
group2 = paste(sample(LETTERS[1:3], 15, replace = TRUE), sample(LETTERS[1:3], 15, replace = TRUE), sep= ","))
edges <- data.frame(id = 1:15, from = trunc(runif(15)*(15-1))+1,
to = trunc(runif(15)*(15-1))+1)
list(nodes = nodes, edges = edges)
})
output$network_proxy_options <- renderVisNetwork({
visNetwork(dataos()$nodes, dataos()$edges) %>% visEdges(arrows = "to") %>%
visLegend()
})
observe({
col <- paste0('rgba(200,200,200,', input$opahigh, ')')
visNetworkProxy("network_proxy_options") %>%
visOptions(highlightNearest = list(enabled = input$highlightNearest, hover = input$hover,
algorithm = input$algorithm, degree = input$deg, hideColor = col))
})
observe({
visNetworkProxy("network_proxy_options") %>%
visOptions(nodesIdSelection = list(enabled = input$nodesIdSelection, selected = 5))
})
observe({
if(input$selectedby){
col <- paste0('rgba(200,200,200,', input$opasel, ')')
visNetworkProxy("network_proxy_options") %>%
visOptions(selectedBy = list(variable = "group", hideColor = col, highlight = input$selectedbyHighlight))
}else{
visNetworkProxy("network_proxy_options") %>%
visOptions(selectedBy = NULL)
}
})
observe({
if(input$open_collapse){
visNetworkProxy("network_proxy_options") %>% visEvents(type = "on", doubleClick = "networkOpenCluster")
} else {
visNetworkProxy("network_proxy_options") %>% visEvents(type = "off", doubleClick = "networkOpenCluster")
}
})
observe({
visNetworkProxy("network_proxy_options") %>%
visOptions(collapse = list(enabled = input$collapse, fit = input$fit_collapse,
resetHighlight = input$reset_collapse,
keepCoord = input$keep_coord,
labelSuffix = input$labelSuffix))
})
output$code_proxy_options <- renderText({
'
# highlight
observe({
col <- paste0("rgba(200,200,200,", input$opahigh, ")")
visNetworkProxy("network_proxy_options") %>%
visOptions(highlightNearest = list(enabled = input$highlightNearest, hover = input$hover,
algorithm = input$algorithm, degree = input$deg, hideColor = col))
})
# nodesIdSelection
observe({
visNetworkProxy("network_proxy_options") %>%
visOptions(nodesIdSelection = list(enabled = input$nodesIdSelection, selected = 5))
})
# selectedBy
observe({
if(input$selectedby){
col <- paste0("rgba(200,200,200,", input$opasel, ")")
visNetworkProxy("network_proxy_options") %>%
visOptions(selectedBy = list(variable = "group", hideColor = col))
}else{
visNetworkProxy("network_proxy_options") %>%
visOptions(selectedBy = NULL)
}
})
# collapse
observe({
visNetworkProxy("network_proxy_options") %>%
visOptions(collapse = list(enabled = input$collapse, fit = input$fit_collapse,
resetHighlight = input$reset_collapse,
keepCoord = input$keep_coord,
labelSuffix = input$labelSuffix))
})
observe({
if(input$open_collapse){
visNetworkProxy("network_id") %>% visEvents(type = "on", doubleClick = "networkOpenCluster")
} else {
visNetworkProxy("network_id") %>% visEvents(type = "off", doubleClick = "networkOpenCluster")
}
})
'
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/server/proxy_options_server.R
|
datass <- reactive({
set.seed(2)
nodes <- data.frame(id = 1:15, label = paste("Label", 1:15),
group = sample(LETTERS[1:3], 15, replace = TRUE))
edges <- data.frame(id = 1:15, from = trunc(runif(15)*(15-1))+1,
to = trunc(runif(15)*(15-1))+1)
list(nodes = nodes, edges = edges)
})
output$network_proxy_select <- renderVisNetwork({
visNetwork(datass()$nodes, datass()$edges) %>% visLegend()
})
observe({
nodes_selection <- input$selnodes
visNetworkProxy("network_proxy_select") %>%
visSelectNodes(id = nodes_selection)
})
observe({
edges_selection <- input$seledges
visNetworkProxy("network_proxy_select") %>%
visSelectEdges(id = edges_selection)
})
# observe({
# nodes_selection <- input$selnodes
# edges_selection <- input$seledges
# visNetworkProxy("network_proxy_select") %>%
# visSetSelection(nodesId = nodes_selection, edgesId = edges_selection)
# })
output$code_proxy_select <- renderText({
'
observe({
nodes_selection <- input$selnodes
visNetworkProxy("network_proxy_select") %>%
visSelectNodes(id = nodes_selection)
})
observe({
edges_selection <- input$seledges
visNetworkProxy("network_proxy_select") %>%
visSelectEdges(id = edges_selection)
})
# or with visSetSelection :
observe({
nodes_selection <- input$selnodes
edges_selection <- input$seledges
visNetworkProxy("network_proxy_select") %>%
visSetSelection(nodesId = nodes_selection, edgesId = edges_selection)
})
'
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/server/proxy_select_server.R
|
datatitle <- reactive({
set.seed(2)
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
list(nodes = nodes, edges = edges)
})
output$network_proxy_set_title <- renderVisNetwork({
visNetwork(datatitle()$nodes, datatitle()$edges) %>% visExport()
})
observe({
visNetworkProxy("network_proxy_set_title") %>%
visSetTitle(main = list(text = input$input_main, hidden = input$hidden_main),
submain = list(text = input$input_submain, hidden = input$hidden_submain),
footer =list(text = input$input_footer, hidden = input$hidden_footer))
})
output$code_proxy_set_title <- renderText({
'
observe({
visNetworkProxy("network_proxy_set_title") %>%
visSetTitle(main = list(text = input$input_main, hidden = input$hidden_main),
submain = list(text = input$input_submain, hidden = input$hidden_submain),
footer =list(text = input$input_footer, hidden = input$hidden_footer))
})
'
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/server/proxy_set_title_server.R
|
n = 20
dataup <- reactive({
set.seed(2)
nodes <- data.frame(id = 1:n, label = paste("Label", 1:n),
group = sample(LETTERS[1:3], n, replace = TRUE))
edges <- data.frame(id = 1:n, from = trunc(runif(n)*(n-1))+1,
to = trunc(runif(n)*(n-1))+1)
list(nodes = nodes, edges = edges)
})
output$network_proxy_update <- renderVisNetwork({
visNetwork(dataup()$nodes, dataup()$edges) %>% visLegend() %>%
visOptions(selectedBy = "group", highlightNearest = TRUE)
})
observe({
input$goUpdate
nodes <- data.frame(id = 1:(n+10),
group = sample(LETTERS[1:5], n+10, replace = TRUE))
edges <- dataup()$edges
edges$color <- sample(c("red", "blue", "yellow"), 1)
visNetworkProxy("network_proxy_update") %>%
visUpdateNodes(nodes = nodes) %>%
visUpdateEdges(edges = edges) %>%
visEvents(type = "on", dragEnd = "function(properties) {
alert('finsih to drag');}")
})
observe({
input$goRemove
visNetworkProxy("network_proxy_update") %>%
visRemoveNodes(id = c(1:5)) %>%
visRemoveEdges(id = c(1:5)) %>%
visEvents(type = "off", dragEnd = "function(properties) {
alert('finsih to drag');}")
})
output$code_proxy_update <- renderText({
'
observe({
input$goUpdate
nodes <- data.frame(id = 1:15,
group = sample(LETTERS[1:5], 15, replace = TRUE))
edges <- data()$edges
edges$color <- sample(c("red", "blue", "yellow"), 1)
visNetworkProxy("network_proxy_update") %>%
visUpdateNodes(nodes = nodes) %>%
visUpdateEdges(edges = edges)
})
observe({
input$goRemove
visNetworkProxy("network_proxy_update") %>%
visRemoveNodes(id = c(1:5)) %>%
visRemoveEdges(id = c(1:5))
})
'
})
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/server/proxy_update_server.R
|
shiny::tabPanel(
title = "Basic",
fluidRow(
column(
width = 6,
verbatimTextOutput("code_network_hello")
),
column(
width = 6,
visNetworkOutput("network_hello",height = "300px")
)
),
hr(),
fluidRow(
column(
width = 12,
div(h3("Second network with icons"), align = "center"),
visNetworkOutput("network_icon"),
verbatimTextOutput("code_network_icon")
)
)
)
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/ui/basic_ui.R
|
shiny::tabPanel(
title = "Manipulation in shiny",
fluidRow(
column(
width = 12,
visNetworkOutput("network_manip",height = "600px"),
fluidRow(
column(
width = 6,
verbatimTextOutput("code_network_manip")
),
column(
width = 3,
HTML("Using manipulation option, you can view current action in shiny
with input$networkid_graphChange")
),
column(
width = 3,
verbatimTextOutput('view_manip')
)
)
)
)
)
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/ui/manip_ui.R
|
shiny::tabPanel(
title = "Shiny custom options",
fluidRow(
column(
width = 12,
visNetworkOutput("network_id",height = "400px"),
fluidRow(
column(
width = 6,
verbatimTextOutput("code_network_id")
),
column(
width = 3,
HTML("Using nodesIdSelection option, you can view current node selection in shiny
with input$networkid_selected"),
HTML("Using highlightNearest option, you can view current highlighted nodes in shiny
with input$networkid_highlight_label_id & input$networkid_highlight_color_id")
),
column(
width = 3,
verbatimTextOutput('view_id'),
verbatimTextOutput('view_highlight_color'),
verbatimTextOutput('view_highlight_label')
)
)
)
),
hr(),
fluidRow(
column(
width = 12,
visNetworkOutput("network_group",height = "600px"),
fluidRow(
column(
width = 6,
verbatimTextOutput("code_network_group")
),
column(
width = 3,
HTML("Using selectedBy option, you can view current variable selection in shiny
with input$networkid_selectedBy")
),
column(
width = 3,
verbatimTextOutput('view_group')
)
)
)
)
)
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/ui/options_ui.R
|
shiny::tabPanel(
title = "Use focus & fit methods",
fluidRow(
column(
width = 4,
selectInput("Focus", "Focus on node :",
c(1:15)),
sliderInput("scale_id", "Focus scale : ", min = 1, max = 4, value = 2),
selectInput("Group", "Focus on group :",
c("ALL", "A", "B", "C"))
),
column(
width = 8,
visNetworkOutput("network_proxy_focus", height = "400px")
)
),
verbatimTextOutput("code_proxy_focus")
)
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/ui/proxy_anim_ui.R
|
shiny::tabPanel(
title = "Get nodes/edges data",
fluidRow(
column(
width = 4,
actionButton("getEdges", "Get edges data"),
actionButton("getNodes", "Get nodes data"),
actionButton("updateGet", "Update data")
),
column(
width = 8,
visNetworkOutput("network_proxy_get", height = "400px")
)
),
verbatimTextOutput("edges_data_from_shiny"),
verbatimTextOutput("nodes_data_from_shiny"),
verbatimTextOutput("code_proxy_get")
)
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/ui/proxy_get_ui.R
|
shiny::tabPanel(
title = "Update nodes/edges properties",
fluidRow(
column(
width = 4,
selectInput("color", "Nodes Color :",
c("blue", "red", "green")),
checkboxInput("shadow", "Shadow", FALSE),
sliderInput("size", "Size : ", min = 10, max = 100, value = 20),
checkboxInput("dashes", "Dashes", FALSE),
checkboxInput("smooth", "Smooth", TRUE)
),
column(
width = 8,
visNetworkOutput("network_proxy_nodes", height = "400px")
)
),
verbatimTextOutput("code_proxy_nodes")
)
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/ui/proxy_nodes_ui.R
|
shiny::tabPanel(
title = "Update options",
fluidRow(
column(
width = 4,
checkboxInput("highlightNearest", "highlight ?", FALSE),
sliderInput("deg", "Degree :", min = 1, max = 10, value = 1),
selectInput("algorithm", "highlight algoritm ", c("all", "hierarchical")),
checkboxInput("hover", "highlight when hover ?", FALSE),
sliderInput("opahigh", "Opacity highlight :", min = 0, max = 1, value = 0.5),
hr(),
checkboxInput("nodesIdSelection", "nodes Selection", FALSE),
hr(),
checkboxInput("selectedby", "Groups Selection", FALSE),
checkboxInput("selectedbyHighlight", "Groups Selection highlight", FALSE),
sliderInput("opasel", "Opacity selection :", min = 0, max = 1, value = 0.5),
hr(),
checkboxInput("collapse", "Enable collapse", FALSE),
checkboxInput("fit_collapse", "Fit after collapse", FALSE),
checkboxInput("reset_collapse", "Reset highlight after collapse", FALSE),
checkboxInput("keep_coord", "keep coordinates ?", TRUE),
textInput("labelSuffix", "label suffix on cluster ?", "(cluster)"),
checkboxInput("open_collapse", "Enable open cluster", FALSE)
),
column(
width = 8,
visNetworkOutput("network_proxy_options", height = "500px")
)
),
verbatimTextOutput("code_proxy_options")
)
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/ui/proxy_options_ui.R
|
shiny::tabPanel(
title = "Select nodes/edges data",
fluidRow(
column(
width = 4,
selectInput(inputId = "selnodes", label = "Nodes selection", choices = 1:15, multiple = TRUE),
selectInput(inputId = "seledges", label = "Edges selection", choices = 1:15, multiple = TRUE)
),
column(
width = 8,
visNetworkOutput("network_proxy_select", height = "400px")
)
),
verbatimTextOutput("code_proxy_select")
)
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/ui/proxy_select_ui.R
|
shiny::tabPanel(
title = "Set / update main, submain, footer",
fluidRow(
column(
width = 4,
h4("main :"),
textInput("input_main", "Main : ", ""),
checkboxInput("hidden_main", "Hidden ?", FALSE),
hr(),
h4("submain :"),
textInput("input_submain", "Submain : ", ""),
checkboxInput("hidden_submain", "Hidden ?", FALSE),
hr(),
h4("footer :"),
textInput("input_footer", "Footer : ", ""),
checkboxInput("hidden_footer", "Hidden ?", FALSE),
hr()
),
column(
width = 8,
visNetworkOutput("network_proxy_set_title", height = "400px")
)
),
verbatimTextOutput("code_proxy_set_title")
)
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/ui/proxy_set_title_ui.R
|
shiny::tabPanel(
title = "Update nodes/edges data",
fluidRow(
column(
width = 4,
actionButton("goUpdate", "Update data"),
actionButton("goRemove", "Remove data")
),
column(
width = 8,
visNetworkOutput("network_proxy_update", height = "400px")
)
),
verbatimTextOutput("code_proxy_update")
)
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/src/ui/proxy_update_ui.R
|
require(shiny)
require(visNetwork)
shiny::shinyUI(shiny::navbarPage(
title = "Examples",
source("./src/ui/basic_ui.R", local = TRUE)$value,
source("./src/ui/options_ui.R", local = TRUE)$value,
source("./src/ui/manip_ui.R", local = TRUE)$value,
navbarMenu(
title = "Use proxy",
source("./src/ui/proxy_nodes_ui.R", local = TRUE)$value,
source("./src/ui/proxy_anim_ui.R", local = TRUE)$value,
source("./src/ui/proxy_update_ui.R", local = TRUE)$value,
source("./src/ui/proxy_options_ui.R", local = TRUE)$value,
source("./src/ui/proxy_select_ui.R", local = TRUE)$value,
source("./src/ui/proxy_get_ui.R", local = TRUE)$value,
source("./src/ui/proxy_set_title_ui.R", local = TRUE)$value
)
))
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/inst/shiny/ui.R
|
---
title: "Introduction to visNetwork"
author: "B. Thieurmel - DataStorm"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Introduction to visNetwork}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
**visNetwork** is a R package for network visualization, using **vis.js** javascript library (https://visjs.org). All the remarks and bugs returns are welcome on github : https://github.com/datastorm-open/visNetwork.
## Minimal example
**visNetwork** needs at least two informations :
* a nodes data.frame, with *id* column
* a edges data.frame, with *from* and *to* columns
```{r}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges, width = "100%")
```
## Find help
Besides the help R functions, a vignette is available, and you can access and read the full javascript API :
```{r, eval = FALSE}
# javascript api
visDocumentation()
vignette("Introduction-to-visNetwork") # with CRAN version
# shiny examples
shiny::runApp(system.file("shiny", package = "visNetwork"))
```
Or visit our online documentation : http://datastorm-open.github.io/visNetwork/.
## Simple individual nodes and edges customization
* Adding more variables on nodes data.frame. See **_visNodes_** for available options.
```{r}
nodes <- data.frame(id = 1:10,
label = paste("Node", 1:10), # add labels on nodes
group = c("GrA", "GrB"), # add groups on nodes
value = 1:10, # size adding value
shape = c("square", "triangle", "box", "circle", "dot", "star",
"ellipse", "database", "text", "diamond"), # control shape of nodes
title = paste0("<p><b>", 1:10,"</b><br>Node !</p>"), # tooltip (html or character)
color = c("darkred", "grey", "orange", "darkblue", "purple"),# color
shadow = c(FALSE, TRUE, FALSE, TRUE, TRUE)) # shadow
head(nodes)
```
* Adding more variables on edges data.frame. See **_visEdges_** for available options.
```{r}
edges <- data.frame(from = sample(1:10, 8), to = sample(1:10, 8),
label = paste("Edge", 1:8), # add labels on edges
length = c(100,500), # length
arrows = c("to", "from", "middle", "middle;to"), # arrows
dashes = c(TRUE, FALSE), # dashes
title = paste("Edge", 1:8), # tooltip (html or character)
smooth = c(FALSE, TRUE), # smooth
shadow = c(FALSE, TRUE, FALSE, TRUE)) # shadow
head(edges)
```
```{r}
visNetwork(nodes, edges, width = "100%")
```
## Global nodes/edges configuration
* Set global options for nodes and edges using **_visNodes_** and **_visEdges_**, and use options per group using **_visGroups_**.
```{r}
nodes <- data.frame(id = 1:5, group = c(rep("A", 2), rep("B", 3)))
edges <- data.frame(from = c(2,5,3,3), to = c(1,2,4,2))
visNetwork(nodes, edges, width = "100%") %>%
visNodes(shape = "square") %>% # square for all nodes
visEdges(arrows ="to") %>% # arrow "to" for all edges
visGroups(groupname = "A", color = "darkblue") %>% # darkblue for group "A"
visGroups(groupname = "B", color = "red") # red for group "B"
```
# Network configuration
Configuration options are available in *visOptions*, *visInteraction*, *visLayout*, *visHierarchicalLayout*, *visPhysics* :
## Example Data
```{r, echo=TRUE}
nb <- 10
nodes <- data.frame(id = 1:nb, label = paste("Label", 1:nb),
group = sample(LETTERS[1:3], nb, replace = TRUE), value = 1:nb,
title = paste0("<p>", 1:nb,"<br>Tooltip !</p>"), stringsAsFactors = FALSE)
edges <- data.frame(from = trunc(runif(nb)*(nb-1))+1,
to = trunc(runif(nb)*(nb-1))+1,
value = rnorm(nb, 10), label = paste("Edge", 1:nb),
title = paste0("<p>", 1:nb,"<br>Edge Tooltip !</p>"))
```
## Add legend
It's possible to add more custom legend on nodes / edges ! Default on groups (like in previous versions) :
```{r}
visNetwork(nodes, edges, width = "100%") %>% visLegend()
```
Or passing data :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visLegend(useGroups = FALSE, addNodes = data.frame(label = "Nodes", shape = "circle"),
addEdges = data.frame(label = "link", color = "black"))
```
## Highlight nearest
You can highlight nearest nodes and edges clicking on a node with **highlightNearest** option :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visOptions(highlightNearest = TRUE)
```
It's now possible to control the degree of depth (visNetwork >= 0.1.2) :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visOptions(highlightNearest = list(enabled =TRUE, degree = 2))
```
## Select by node id
You can also select nodes by id/label with a list with **nodesIdSelection** :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)
```
## Select by a column
And select some nodes by the values of a column using **selectedBy** option :
```{r}
# can be the column you want
nodes$sel <- sample(c("sel1", "sel2"), nrow(nodes), replace = TRUE)
visNetwork(nodes, edges, width = "100%") %>%
visOptions(selectedBy = "sel")
```
## Directed Network
```{r, echo = FALSE}
nodes <- data.frame(id = 1:nb, label = paste("Label", 1:nb),
group = sample(1:nb, nb, replace = TRUE), value = 1:nb,
title = paste0("<p>", 1:nb,"<br>Tooltip !</p>"), stringsAsFactors = FALSE)
edges <- data.frame(from = trunc(runif(nb)*(nb-1))+1,
to = trunc(runif(nb)*(nb-1))+1,
title = paste0("<p>", 1:nb,"<br>Edge Tooltip !</p>"))
```
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visEdges(arrows = 'from')
```
## Custom navigation
*vis.js* propose some navigation tools :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visInteraction(navigationButtons = TRUE)
```
## Data Manipulation
And some data manipulation tools :
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visOptions(manipulation = TRUE)
```
## Hierarchical Layout
You can use and control hierarchical layout with *visHierarchicalLayout* and *visLayout* :
```{r, echo = TRUE}
nodes <- data.frame(id = 1:7)
edges <- data.frame(
from = c(1,2,2,2,3,3),
to = c(2,3,4,5,6,7)
)
```
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visEdges(arrows = "from") %>%
visHierarchicalLayout()
# same as visLayout(hierarchical = TRUE)
visNetwork(nodes, edges, width = "100%") %>%
visEdges(arrows = "from") %>%
visHierarchicalLayout(direction = "LR")
```
## Freeze network
```{r}
visNetwork(nodes, edges, width = "100%") %>%
visInteraction(dragNodes = FALSE, dragView = FALSE, zoomView = FALSE)
```
# Additional features
## Use font awesome icons in your network
You can use **Font Awesome** icons using groups or nodes options. **Font Awesome** library (https://fontawesome.com/) is not part of default dependencies. use addFontAwesome() if needed.
```{r, eval = FALSE}
# don't run here
nodes <- data.frame(id = 1:3, group = c("B", "A", "B"))
edges <- data.frame(from = c(1,2), to = c(2,3))
visNetwork(nodes, edges, width = "100%") %>%
visGroups(groupname = "A", shape = "icon", icon = list(code = "f0c0", size = 75)) %>%
visGroups(groupname = "B", shape = "icon", icon = list(code = "f007", color = "red")) %>%
visLegend() %>%
addFontAwesome()
```
## Visualize rpart object
New *visTree* function allows to visualize and customize a *rpart* classification and regression tree. Have a look to *visTreeEditor* to edity and get back network, or to *visTreeModuleServer* to use custom tree module in R.
```{r, eval = T}
library(rpart)
# Complex tree
data("solder")
res <- rpart(Opening~., data = solder, control = rpart.control(cp = 0.00005))
visTree(res, height = "800px", nodesPopSize = TRUE, minNodeSize = 10, maxNodeSize = 30)
```
## Use in Shiny
With *visNetworkOutput* and *renderVisNetwork*. Using with shiny, and enabled options *nodesIdSelection*, you can access to new input with current selection value. Morevoer, you can do a lot of things with *visNetworkProxy*
```{r, eval = FALSE}
output$mynetwork <- renderVisNetwork({... visOptions(nodesIdSelection = TRUE)}) # created input$mynetwork_selected
```
And with *selectedBy*, new input __input$mynetwork_selectedBy__.
## Physics, tooltip, events,
You can also control :
* physics of network : *visPhysics*
* events : *visEvents*
## Export
```{r, eval = FALSE}
network <- visNetwork(nodes, edges, width = "100%")
visSave(network, file = "network.html")
```
## Use DOT language data
```{r}
visNetwork(dot = 'dinetwork {1 -> 1 -> 2; 2 -> 3; 2 -- 4; 2 -> 1 }', width = "100%")
```
## Use gephi json export file
```{r, eval = FALSE}
# don't run here
visNetwork(gephi = 'WorldCup2014.json')
```
|
/scratch/gouwar.j/cran-all/cranData/visNetwork/vignettes/Introduction-to-visNetwork.Rmd
|
#' @keywords internal
"_PACKAGE"
## usethis namespace: start
#' @importFrom rlang .data
#' @importFrom rlang .env
#' @importFrom rlang :=
## usethis namespace: end
NULL
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/VisOmop-package.R
|
# Assertions ----
#' Assert if an object is a character and fulfill certain conditions.
#'
#' @param x To check.
#' @param length Length that has to have.
#' @param na Whether it can contain NA values.
#' @param null Whether it can be null.
#' @param named Whether it has to be named.
#' @param minNumCharacter Minimum number of characters.
#' @param call Call argument that will be passed to `cli`.
#'
#' @noRd
#'
assertCharacter <- function(x,
length = NULL,
na = FALSE,
null = FALSE,
named = FALSE,
minNumCharacter = 0,
call = parent.frame()) {
# create error message
errorMessage <- paste0(
paste0(substitute(x), collapse = ""),
" must be a character",
errorLength(length),
errorNa(na),
errorNull(null),
errorNamed(named),
ifelse(
minNumCharacter > 0,
paste("; at least", minNumCharacter, "per element"),
""
),
"."
)
# assert null
if (assertNull(x, null, errorMessage, call)) {
# no NA vector
xNoNa <- x[!is.na(x)]
# assert class
if (!is.character(x)) {
cli::cli_abort(errorMessage, call = call)
}
# assert length
assertLength(x, length, errorMessage, call)
# assert na
assertNa(x, na, errorMessage, call)
# assert named
assertNamed(x, named, errorMessage, call)
# minimum number of characters
if (any(nchar(xNoNa) < minNumCharacter)) {
cli::cli_abort(errorMessage, call = call)
}
}
return(invisible(x))
}
#' Assert if an object is a list and fulfill certain conditions.
#'
#' @param x To check.
#' @param length Length that has to have.
#' @param na Whether it can contain NA values.
#' @param null Whether it can be null.
#' @param named Whether it has to be named.
#' @param class Class that elements must have.
#' @param call Call argument that will be passed to `cli`.
#'
#' @noRd
#'
assertList <- function(x,
length = NULL,
na = FALSE,
null = FALSE,
named = FALSE,
class = NULL,
call = parent.frame()) {
# create error message
errorMessage <- paste0(
paste0(substitute(x), collapse = ""),
" must be a list",
errorLength(length),
errorNa(na),
errorNull(null),
errorNamed(named),
ifelse(
!is.null(class),
paste("; elements must have class:", paste0(class, collapse = ", ")),
""
),
"."
)
# assert null
if (assertNull(x, null, errorMessage, call)) {
# no NA vector
xNoNa <- x[!is.na(x)]
# assert class
if (!is.list(x)) {
cli::cli_abort(errorMessage, call = call)
}
# assert length
assertLength(x, length, errorMessage, call)
# assert na
assertNa(x, na, errorMessage, call)
# assert named
assertNamed(x, named, errorMessage, call)
# assert class
if (!is.null(class)) {
flag <- lapply(xNoNa, function(y) {
any(class %in% base::class(y))
}) |>
unlist() |>
all()
if (flag != TRUE) {
cli::cli_abort(errorMessage, call = call)
}
}
}
return(invisible(x))
}
#' Assert if an object is a choice and fulfill certain conditions.
#'
#' @param x To check.
#' @param choices Options that x can be.
#' @param length Length that has to have.
#' @param na Whether it can contain NA values.
#' @param null Whether it can be null.
#' @param named Whether it has to be named.
#' @param call Call argument that will be passed to `cli`.
#'
#' @noRd
#'
assertChoice <- function(x,
choices,
length = NULL,
na = FALSE,
null = FALSE,
named = FALSE,
call = parent.frame()) {
# create error message
errorMessage <- paste0(
paste0(substitute(x), collapse = ""),
" must be a choice between: ",
paste0(choices, collapse = ", "),
errorLength(length),
errorNa(na),
errorNull(null),
errorNamed(named),
"."
)
# assert null
if (assertNull(x, null, errorMessage, call)) {
# no NA vector
xNoNa <- x[!is.na(x)]
# assert class
if (!all(class(x) == class(choices))) {
cli::cli_abort(errorMessage, call = call)
}
# assert length
assertLength(x, length, errorMessage, call)
# assert na
assertNa(x, na, errorMessage, call)
# assert named
assertNamed(x, named, errorMessage, call)
# assert choices
if (base::length(xNoNa) > 0) {
if (!all(xNoNa %in% choices)) {
cli::cli_abort(errorMessage, call = call)
}
}
}
return(invisible(x))
}
#' Assert if an object is a logical and fulfill certain conditions.
#'
#' @param x To check.
#' @param length Length that has to have.
#' @param na Whether it can contain NA values.
#' @param null Whether it can be null.
#' @param named Whether it has to be named.
#' @param call Call argument that will be passed to `cli`.
#'
#' @noRd
#'
assertLogical <- function(x,
length = NULL,
na = FALSE,
null = FALSE,
named = FALSE,
call = parent.frame()) {
# create error message
errorMessage <- paste0(
paste0(substitute(x), collapse = ""),
" must be a logical",
errorLength(length),
errorNa(na),
errorNull(null),
errorNamed(named),
"."
)
# assert null
if (assertNull(x, null, errorMessage, call)) {
# assert class
if (!is.logical(x)) {
cli::cli_abort(errorMessage, call = call)
}
# assert length
assertLength(x, length, errorMessage, call)
# assert na
assertNa(x, na, errorMessage, call)
# assert named
assertNamed(x, named, errorMessage, call)
}
return(invisible(x))
}
#' Assert if an object is a numeric and fulfill certain conditions.
#'
#' @param x To check.
#' @param integerish Whether elements must be integerish.
#' @param min Lower bound.
#' @param max Upper bound.
#' @param length Length that has to have.
#' @param na Whether it can contain NA values.
#' @param null Whether it can be null.
#' @param named Whether it has to be named.
#' @param call Call argument that will be passed to `cli`.
#'
#' @noRd
#'
assertNumeric <- function(x,
integerish = FALSE,
min = -Inf,
max = Inf,
length = NULL,
na = FALSE,
null = FALSE,
named = FALSE,
call = parent.frame()) {
# create error message
errorMessage <- paste0(
paste0(substitute(x), collapse = ""),
" must be a numeric",
ifelse(integerish, "; it has to be integerish", ""),
ifelse(is.infinite(min), "", paste0("; equal or greater than ", min)),
ifelse(is.infinite(max), "", paste0("; smaller than ", max)),
errorLength(length),
errorNa(na),
errorNull(null),
errorNamed(named),
"."
)
# assert null
if (assertNull(x, null, errorMessage, call)) {
# no NA vector
xNoNa <- x[!is.na(x)]
# assert class
if (!is.numeric(x)) {
cli::cli_abort(errorMessage, call = call)
}
# assert integerish
if (integerish & base::length(xNoNa) > 0) {
err <- max(abs(xNoNa - round(xNoNa)))
if (err > 0.0001) {
cli::cli_abort(errorMessage, call = call)
}
}
# assert lower bound
if (!is.infinite(min) & base::length(xNoNa) > 0) {
if (base::min(xNoNa) < min) {
cli::cli_abort(errorMessage, call = call)
}
}
# assert upper bound
if (!is.infinite(max) & base::length(xNoNa) > 0) {
if (base::max(xNoNa) > max) {
cli::cli_abort(errorMessage, call = call)
}
}
# assert length
assertLength(x, length, errorMessage, call)
# assert na
assertNa(x, na, errorMessage, call)
# assert named
assertNamed(x, named, errorMessage, call)
}
return(invisible(x))
}
#' Assert if an object is a tibble and fulfill certain conditions.
#'
#' @param x To check.
#' @param numberColumns Number of columns.
#' @param numberRows Number of rows.
#' @param columns Name of columns that must be present.
#' @param null Whether it can be null.
#' @param call Call argument that will be passed to `cli`.
#'
#' @noRd
#'
assertTibble <- function(x,
numberColumns = NULL,
numberRows = NULL,
columns = NULL,
null = FALSE,
call = parent.frame()) {
# create error message
errorMessage <- paste0(
paste0(substitute(x), collapse = ""),
" must be a tibble",
ifelse(is.null(numberColumns), "", paste0("; with at least ", numberColumns, " columns")),
ifelse(is.null(numberRows), "", paste0("; with at least ", numberRows, " rows")),
ifelse(is.null(columns), "", paste0("; the following columns must be present: ", paste0(columns, collapse = ", "))),
errorNull(null),
"."
)
# assert null
if (assertNull(x, null, errorMessage, call)) {
# assert class
if (!("tbl" %in% class(x))) {
cli::cli_abort(errorMessage, call = call)
}
# assert numberColumns
if (!is.null(numberColumns)) {
if (length(x) != numberColumns) {
cli::cli_abort(errorMessage, call = call)
}
}
# assert numberRows
if (!is.null(numberRows)) {
if (nrow(x) != numberRows) {
cli::cli_abort(errorMessage, call = call)
}
}
# assert columns
if (!is.null(columns)) {
if (!all(columns %in% colnames(x))) {
cli::cli_abort(errorMessage, call = call)
}
}
}
return(invisible(x))
}
assertLength <- function(x, length, errorMessage, call) {
if (!is.null(length) && base::length(x) != length) {
cli::cli_abort(errorMessage, call = call)
}
invisible(x)
}
assertNa <- function(x, na, errorMessage, call) {
if (!na && any(is.na(x))) {
cli::cli_abort(errorMessage, call = call)
}
invisible(x)
}
assertNamed <- function(x, named, errorMessage, call) {
if (named && length(names(x)[names(x) != ""]) != length(x)) {
cli::cli_abort(errorMessage, call = call)
}
invisible(x)
}
assertNull <- function(x, null, errorMessage, call) {
if (!null && is.null(x)) {
cli::cli_abort(errorMessage, call = call)
}
return(!is.null(x))
}
#' Assert that an object has a certain class.
#'
#' @param x To check.
#' @param class Expected class or classes.
#' @param call Call argument that will be passed to `cli`.
#'
#' @noRd
#'
assertClass <- function(x,
class,
call = parent.frame()) {
# create error message
errorMessage <- paste0(
paste0(substitute(x), collapse = ""), " must have class: ",
paste0(class, collapse = ", "), "; but has class: ",
paste0(base::class(x), collapse = ", "), "."
)
if (!all(class %in% base::class(x))) {
cli::cli_abort(errorMessage, call = call)
}
invisible(x)
}
#' Assert that an object is a Date.
#'
#' @param x To check.
#' @param length Length that has to have.
#' @param call Call argument that will be passed to `cli`.
#'
#' @noRd
#'
assertDate <- function(x,
length,
call = parent.frame()) {
# create error message
errorMessage <- paste0(substitute(x), " must be an object of class Date.")
if (! class(x) %in% "Date") {
cli::cli_abort(errorMessage, call = call)
}
errorMessage <- paste0(substitute(x), " must have length = ", length)
if (length(x) != length) {
cli::cli_abort(errorMessage, call = call)
}
invisible(x)
}
# Error messages ----
errorLength <- function(length) {
if (!is.null(length)) {
str <- paste0("; with length = ", length)
} else {
str <- ""
}
return(str)
}
errorNa <- function(na) {
if (na) {
str <- ""
} else {
str <- "; it can not contain NA"
}
return(str)
}
errorNamed <- function(named) {
if (named) {
str <- "; it has to be named"
} else {
str <- ""
}
return(str)
}
errorNull <- function(null) {
if (null) {
str <- ""
} else {
str <- "; it can not be NULL"
}
return(str)
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/assertions.R
|
#' Identify group columns in an omop result object
#'
#' @param result A summarised_result.
#' @param overall deprecated.
#'
#' @return Unique values of the group name column.
#' @description Identifies and returns the unique values in group_name column.
#'
#' @export
#'
#' @examples
#' mockSummarisedResult() |>
#' groupColumns()
#'
groupColumns <- function(result, overall = lifecycle::deprecated()) {
if (lifecycle::is_present(overall)) {
lifecycle::deprecate_warn("0.1.1", "groupColumns(overall)")
}
getColumns(result = result, col = "group_name")
}
#' Identify strata columns in an omop result object
#'
#' @param result A summarised_result.
#' @param overall deprecated.
#'
#' @return Unique values of the strata name column.
#' @description Identifies and returns the unique values in strata_name column.
#'
#' @export
#'
#' @examples
#' mockSummarisedResult() |>
#' strataColumns()
#'
strataColumns <- function(result, overall = lifecycle::deprecated()) {
if (lifecycle::is_present(overall)) {
lifecycle::deprecate_warn("0.1.1", "strataColumns(overall)")
}
getColumns(result = result, col = "strata_name")
}
#' Identify additional columns in an omop result object
#'
#' @param result A summarised_result.
#' @param overall deprecated.
#'
#' @return Unique values of the additional name column.
#' @description Identifies and returns the unique values in additional_name
#' column.
#'
#' @export
#'
#' @examples
#' mockSummarisedResult() |>
#' additionalColumns()
#'
additionalColumns <- function(result, overall = lifecycle::deprecated()) {
if (lifecycle::is_present(overall)) {
lifecycle::deprecate_warn("0.1.1", "additionalColumns(overall)")
}
getColumns(result = result, col = "additional_name")
}
getColumns <- function(result, col) {
# initial checks
assertTibble(result, columns = col)
assertCharacter(col, length = 1)
# extract columns
x <- result |>
dplyr::pull(dplyr::all_of(col)) |>
unique() |>
lapply(strsplit, split = " and | &&& ") |>
unlist() |>
unique()
# eliminate overall
x <- x[x != "overall"]
return(x)
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/columns.R
|
#' Formats estimate_name and estimate_value column
#'
#' @param result A summarised_result.
#' @param estimateNameFormat Named list of estimate name's to join, sorted by
#' computation order. Indicate estimate_name's between <...>.
#' @param keepNotFormatted Whether to keep rows not formatted.
#' @param useFormatOrder Whether to use the order in which estimate names
#' appear in the estimateNameFormat (TRUE), or use the order in the
#' input dataframe (FALSE).
#'
#' @description
#' Formats estimate_name and estimate_value columns by changing the name of the
#' estimate name and/or joining different estimates together in a single row.
#'
#' @return A summarised_result object.
#'
#' @export
#'
#' @examples
#' result <- mockSummarisedResult()
#' result |>
#' formatEstimateName(
#' estimateNameFormat = c(
#' "N (%)" = "<count> (<percentage>%)", "N" = "<count>"
#' ),
#' keepNotFormatted = FALSE
#' )
#'
formatEstimateName <- function(result,
estimateNameFormat = NULL,
keepNotFormatted = TRUE,
useFormatOrder = TRUE) {
# initial checks
# result <- validateResult(result)
assertTibble(result, columns = c("estimate_name", "estimate_value"))
estimateNameFormat <- validateEstimateNameFormat(estimateNameFormat)
assertCharacter(estimateNameFormat, null = TRUE)
assertLogical(keepNotFormatted, length = 1)
assertLogical(useFormatOrder, length = 1)
# format estimate
if (!is.null(estimateNameFormat)) {
resultFormatted <- formatEstimateNameInternal(
result = result, format = estimateNameFormat,
keepNotFormatted = keepNotFormatted, useFormatOrder = useFormatOrder
)
} else {
resultFormatted <- result
}
return(resultFormatted)
}
formatEstimateNameInternal <- function(result, format, keepNotFormatted, useFormatOrder) {
# if no format no action is performed
if (length(format) == 0) {
return(result)
}
# correct names
if (is.null(names(format))) {
nms <- rep("", length(format))
} else {
nms <- names(format)
}
nms[nms == ""] <- gsub("<|>", "", format[nms == ""])
# format
ocols <- colnames(result)
cols <- ocols[
!ocols %in% c("estimate_name", "estimate_type", "estimate_value")
]
# start formatting
result <- result |>
dplyr::mutate("formatted" = FALSE, "id" = dplyr::row_number()) |>
dplyr::group_by(dplyr::across(dplyr::all_of(cols))) |>
dplyr::mutate(group_id = min(.data$id)) |>
dplyr::ungroup()
resultF <- NULL
for (k in seq_along(format)) {
nameK <- nms[k]
formatK <- format[k] |> unname()
keys <- result[["estimate_name"]] |> unique()
keysK <- regmatches(formatK, gregexpr("(?<=\\<).+?(?=\\>)", formatK, perl = T))[[1]]
format_boolean <- all(keysK %in% keys)
len <- length(keysK)
if (len > 0 & format_boolean) {
formatKNum <- getFormatNum(formatK, keysK)
res <- result |>
dplyr::filter(!.data$formatted) |>
dplyr::filter(.data$estimate_name %in% .env$keysK) |>
dplyr::group_by(dplyr::across(dplyr::all_of(cols))) |>
dplyr::filter(dplyr::n() == .env$len) |>
dplyr::mutate("id" = min(.data$id))
resF <- res |>
dplyr::ungroup() |>
dplyr::select(-"estimate_type") |>
tidyr::pivot_wider(
names_from = "estimate_name", values_from = "estimate_value"
) |>
evalName(formatKNum, keysK) |>
dplyr::mutate(
"estimate_name" = nameK,
"formatted" = TRUE,
"estimate_type" = "character"
) |>
dplyr::select(dplyr::all_of(c(ocols, "id", "group_id", "formatted")))
result <- result |>
dplyr::anti_join(
res |> dplyr::select(dplyr::all_of(c(cols, "estimate_name"))),
by = c(cols, "estimate_name")
) |>
dplyr::union_all(resF)
} else {
if (len > 0) {warning(paste0(formatK, " has not been formatted."), call. = FALSE)
} else {warning(paste0(formatK, " does not contain an estimate name indicated by <...>"), call. = FALSE)}
}
}
#useFormatOrder
if (useFormatOrder) {
new_order <- dplyr::tibble(estimate_name = nms, format_id = 1:length(nms)) |>
dplyr::union_all(result |>
dplyr::select("estimate_name") |>
dplyr::distinct() |>
dplyr::filter(!.data$estimate_name %in% nms) |>
dplyr::mutate(format_id = length(format) + dplyr::row_number()))
result <- result |>
dplyr::left_join(new_order,
by = "estimate_name")
result <- result[order(result$group_id, result$format_id, decreasing = FALSE),] |>
dplyr::select(-c("id", "group_id", "format_id"))
} else {
result <- result |>
dplyr::arrange(.data$id) |>
dplyr::select(-"id", -"group_id")
}
# keepNotFormated
if (!keepNotFormatted) {
result <- result |> dplyr::filter(.data$formatted)
}
# result
result <- result |> dplyr::select(-"formatted")
return(result)
}
getFormatNum <- function(format, keys) {
ik <- 1
for (k in seq_along(keys)) {
format <- gsub(
pattern = keys[k], replacement = paste0("#", ik, "#"), x = format
)
ik <- ik + 1
}
return(format)
}
evalName <- function(result, format, keys) {
for (k in seq_along(keys)) {
format <- gsub(
pattern = paste0("<#", k, "#>"),
replacement = paste0("#x#.data[[\"", keys[k], "\"]]#x#"),
x = format
)
}
format <- strsplit(x = format, split = "#x#") |> unlist()
format <- format[format != ""]
id <- !startsWith(format, ".data")
format[id] <- paste0("\"", format[id], "\"")
format <- paste0(format, collapse = ", ")
format <- paste0("paste0(", format, ")")
result <- result |>
dplyr::mutate("estimate_value" = eval(parse(text = format)))
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/formatEstimateName.R
|
#' Formats the estimate_value column
#'
#' @param result A summarised_result.
#' @param decimals Number of decimals per estimate type (integer, numeric,
#' percentage, proportion), estimate name, or all estimate values (introduce the
#' number of decimals).
#' @param decimalMark Decimal separator mark.
#' @param bigMark Thousand and millions separator mark.
#'
#' @return A summarised_result.
#'
#' @description
#' Formats the estimate_value column of summarised_result object by editing
#' number of decimals, decimal and thousand/millions separator marks.
#'
#'
#' @export
#'
#' @examples
#' result <- mockSummarisedResult()
#'
#' result |> formatEstimateValue(decimals = 1)
#'
#' result |> formatEstimateValue(decimals = c(integer = 0, numeric = 1))
#'
#' result |>
#' formatEstimateValue(decimals = c(numeric = 1, count = 0))
formatEstimateValue <- function(result,
decimals = c(
integer = 0, numeric = 2, percentage = 1,
proportion = 3
),
decimalMark = ".",
bigMark = ",") {
# initial checks
assertTibble(result, columns = c("estimate_name", "estimate_type", "estimate_value"))
decimals <- validateDecimals(result, decimals)
assertCharacter(decimalMark, length = 1)
assertCharacter(bigMark, length = 1, null = TRUE)
if (is.null(bigMark)) {bigMark <- ""}
result <- formatEstimateValueInternal(result, decimals, decimalMark, bigMark)
return(result)
}
formatEstimateValueInternal <- function(result, decimals, decimalMark, bigMark) {
nms_name <- unique(result[["estimate_name"]])
if (is.null(decimals)) { # default # decimal formatting
for (nm in nms_name) {
result$estimate_value[result[["estimate_name"]] == nm] <- result$estimate_value[result[["estimate_name"]] == nm] |>
as.numeric() |>
base::format(big.mark = bigMark, decimal.mark = decimalMark, trim = TRUE, justify = "none")
}
} else {
formatted <- rep(FALSE, nrow(result))
for (nm in names(decimals)) {
if (nm %in% nms_name) {
id <- result[["estimate_name"]] == nm & !formatted & !is.na(result$estimate_value) & !grepl("<", result$estimate_value)
} else {
id <- result[["estimate_type"]] == nm & !formatted & !is.na(result$estimate_value) & !grepl("<", result$estimate_value)
}
n <- decimals[nm] |> unname()
result$estimate_value[id] <- result$estimate_value[id] |>
as.numeric() |>
round(digits = n) |>
base::format(nsmall = n, big.mark = bigMark, decimal.mark = decimalMark, trim = TRUE, justify = "none")
formatted[id] <- TRUE
}
}
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/formatEstimateValue.R
|
#' Creats a header for gt and flextable objects.
#'
#' @param result A summarised_result.
#' @param header Names of the columns to make headers. Names that doesn't
#' correspond to a column of the table result, will be used as headers at the
#' defined position.
#' @param delim Delimiter to use to separate headers.
#' @param includeHeaderName Whether to include the column name as header.
#' @param includeHeaderKey Whether to include the header key (header,
#' header_name, header_level) before each header type in the column names.
#'
#' @return A tibble with rows pivotted into columns with key names for
#' subsequent header formatting.
#'
#' @description
#' Pivots a summarised_result object based on the column names in header,
#' generating specific column names for subsequent header formatting in
#' gtTable and fxTable functions.
#'
#' @export
#'
#' @examples
#' result <- mockSummarisedResult()
#'
#' result |>
#' formatHeader(
#' header = c(
#' "Study cohorts", "group_level", "Study strata", "strata_name",
#' "strata_level"
#' ),
#' includeHeaderName = FALSE
#' )
formatHeader <- function(result,
header,
delim = "\n",
includeHeaderName = TRUE,
includeHeaderKey = TRUE) {
# initial checks
assertTibble(result)
assertCharacter(header, null = TRUE)
assertCharacter(delim, length = 1)
assertLogical(includeHeaderName, length = 1)
validateDelim(delim)
if (!is.null(header)) {
if (length(header) > 0) {
# correct names
nms <- names(header)
if (is.null(nms)) {
nms <- rep("", length(header))
}
nms[nms == ""] <- header[nms == ""]
# pivot wider
cols <- header[header %in% colnames(result)] |> unname()
if (length(cols) > 0) {
colDetails <- result |>
dplyr::select(dplyr::all_of(cols)) |>
dplyr::distinct() |>
dplyr::mutate("name" = sprintf("column%03i", dplyr::row_number()))
result <- result |>
dplyr::inner_join(colDetails, by = cols) |>
dplyr::select(-dplyr::all_of(cols)) |>
tidyr::pivot_wider(names_from = "name", values_from = "estimate_value")
columns <- colDetails$name
# create column names
colDetails <- colDetails |> dplyr::mutate(new_name = "")
for (k in seq_along(header)) {
if (header[k] %in% cols) { # Header in dataframe
spanners <- colDetails[[header[k]]] |> unique()
for (span in spanners) { # loop through column values
if (!is.na(span)) {
colsSpanner <- colDetails[[header[k]]] == span
if (includeHeaderKey) {
if (includeHeaderName) {
colDetails$new_name[colsSpanner] <- paste0(colDetails$new_name[colsSpanner], "[header_name]", nms[k], delim, "[header_level]", span, delim)
} else {
colDetails$new_name[colsSpanner] <- paste0(colDetails$new_name[colsSpanner], "[header_level]", span, delim)
}
} else {
if (includeHeaderName) {
colDetails$new_name[colsSpanner] <- paste0(colDetails$new_name[colsSpanner], nms[k], delim, span, delim)
} else {
colDetails$new_name[colsSpanner] <- paste0(colDetails$new_name[colsSpanner], span, delim)
}
}
} else {
cli::cli_abort(paste0("There are missing levels in '", header[k], "'."))
}
}
} else {
if (includeHeaderKey) {
colDetails$new_name <- paste0(colDetails$new_name, "[header]", nms[k], delim)
} else {
colDetails$new_name <- paste0(colDetails$new_name, nms[k], delim)
}
}
}
colDetails <- colDetails |> dplyr::mutate(new_name = base::substring(.data$new_name, 0, nchar(.data$new_name)-1))
# add column names
names(result)[names(result) %in% colDetails$name] <- colDetails$new_name
} else {
if (includeHeaderKey) {
new_name <- paste0("[header]", paste(header, collapse = paste0(delim, "[header]")))
} else {
new_name <- paste(header, collapse = delim)
}
result <- result |> dplyr::rename(!!new_name := "estimate_value")
class(result) <- c("tbl_df", "tbl", "data.frame")
}
}
}
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/formatHeader.R
|
#' Format a summarised_result object into a gt, flextable or tibble object
#'
#' @param result A summarised_result.
#' @param formatEstimateName Named list of estimate name's to join, sorted by
#' computation order. Indicate estimate_name's between <...>.
#' @param header A vector containing which elements should go into the header
#' in order. Allowed are: `cdm_name`, `group`, `strata`, `additional`,
#' `variable`, `estimate`, `settings`.
#' @param groupColumn Column to use as group labels.
#' @param split A vector containing the name-level groups to split ("group",
#' "strata", "additional"), or an empty character vector to not split.
#' @param type Type of desired formatted table, possibilities: "gt",
#' "flextable", "tibble".
#' @param minCellCount Counts below which results will be clouded.
#' @param excludeColumns Columns to drop from the output table.
#' @param .options Named list with additional formatting options.
#' visOmopResults::optionsFormatTable() shows allowed arguments and
#' their default values.
#'
#' @return A tibble, gt, or flextable object.
#'
#'
#' @export
#'
#' @examples
#' mockSummarisedResult() |> formatTable(
#' formatEstimateName = c("N%" = "<count> (<percentage>)",
#' "N" = "<count>",
#' "Mean (SD)" = "<mean> (<sd>)"),
#' header = c("group"),
#' split = c("group","strata", "additional")
#' )
#'
formatTable <- function(result,
formatEstimateName,
header,
split,
groupColumn = NULL,
type = "gt",
minCellCount = 5,
excludeColumns = c("result_id", "result_type", "package_name", "package_version", "estimate_type"),
.options = list()) {
# initial checks
result <- omopgenerics::newSummarisedResult(result)
assertChoice(type, c("gt", "flextable", "tibble"))
assertCharacter(formatEstimateName)
assertCharacter(header)
assertCharacter(groupColumn, null = TRUE, length = 1)
assertCharacter(split)
assertCharacter(excludeColumns, null = TRUE)
assertNumeric(minCellCount, length = 1, null = FALSE, integerish = TRUE)
assertList(.options)
if (length(split) > 0) {
if (!all(split %in% c("group", "strata", "additional"))) {
cli::cli_abort("Accepted values for split are: `group`, `strata`, and/or `additional`. It also supports an empty character vector (`character()`).")
}
}
if ("cdm_name" %in% header & "cdm_name" %in% excludeColumns) {
cli::cli_abort("`cdm_name` cannot be part of the header and also an excluded column.")
}
if(!all(header %in% c("cdm_name", "group", "strata", "additional", "estimate", "variable", "settings"))) {
cli::cli_abort("Allowed values in header vector are: `cdm_name`, `group`, `strata`, `additional`, `estimate`, `variable`, and `settings`.")
}
# settings
settings <- omopgenerics::settings(result)
result <- result |> dplyr::filter(.data$variable_name != "settings")
# .options
.options <- defaultTableOptions(.options)
# Supress counts & format estimates ----
x <- result |>
# think how to better handle min cell count in this process (formatEstimateName --> nothing if any is NA)
omopgenerics::suppress(minCellCount = minCellCount) |>
dplyr::mutate(estimate_value = dplyr::if_else(
is.na(.data$estimate_value), paste0("<", .env$minCellCount), .data$estimate_value
)) |>
visOmopResults::formatEstimateValue(
decimals = .options$decimals,
decimalMark = .options$decimalMark,
bigMark = .options$bigMark
) |>
visOmopResults::formatEstimateName(
estimateNameFormat = formatEstimateName,
keepNotFormatted = .options$keepNotFormatted,
useFormatOrder = .options$useFormatOrder
)
# Split & prepare header ----
# Group:
splitGroup <- "group" %in% split
headerGroup <- "group" %in% header
colsGroup <- character()
if (headerGroup & splitGroup) {
colsGroup <- visOmopResults::groupColumns(result)
colsGroup <- lapply(as.list(colsGroup), function(element) {c(formatString(element), element)}) |> unlist()
x <- x |> visOmopResults::splitGroup()
} else if (headerGroup & !splitGroup) {
if (length(visOmopResults::groupColumns(result)) > 0) {
colsGroup <- c("group_name", "group_level")
} else {
x <- x |> visOmopResults::splitGroup()
}
} else if (!headerGroup & splitGroup) {
x <- x |> visOmopResults::splitGroup()
}
# Strata:
splitStrata <- "strata" %in% split
headerStrata <- "strata" %in% header
colsStrata <- character()
if (headerStrata & splitStrata) {
colsStrata <- visOmopResults::strataColumns(result)
colsStrata <- lapply(as.list(colsStrata), function(element) {c(formatString(element), element)}) |> unlist()
x <- x |> visOmopResults::splitStrata()
} else if (headerStrata & !splitStrata) {
if (length(visOmopResults::strataColumns(result)) > 0) {
colsStrata <- c("strata_name", "strata_level")
} else {
x <- x |> visOmopResults::splitStrata()
}
} else if (!headerStrata & splitStrata) {
x <- x |> visOmopResults::splitStrata()
}
# Additional:
splitAdditional <- "additional" %in% split
headerAdditional <- "additional" %in% header
colsAdditional <- character()
if (headerAdditional & splitAdditional) {
colsAdditional <- visOmopResults::additionalColumns(result)
colsAdditional <- lapply(as.list(colsAdditional), function(element) {c(formatString(element), element)}) |> unlist()
x <- x |> visOmopResults::splitAdditional()
} else if (headerAdditional & !splitAdditional) {
if (length(visOmopResults::additionalColumns(result)) > 0) {
colsAdditional <- c("additional_name", "additional_level")
} else {
x <- x |> visOmopResults::splitAdditional()
}
} else if (!headerAdditional & splitAdditional) {
x <- x |> visOmopResults::splitAdditional()
}
# Others:
colsVariable <- character()
if ("variable" %in% header) {
colsVariable = c("variable_name", "variable_level")
x <- x |>
dplyr::mutate(dplyr::across(dplyr::starts_with("variable"), ~ dplyr::if_else(is.na(.x), .options$na, .x)))
}
colsEstimate <- character()
if ("estimate" %in% header) {
colsEstimate = c("estimate_name")
}
colsSettings <- character()
if ("settings" %in% header) {
colsSettings <- colnames(settings)
colsSettings <- colsSettings[!colsSettings %in% c("result_id", "cdm_name", "result_type")]
if (length(colsSettings) > 0) {
x <- x |>
dplyr::left_join(
settings |>
tidyr::pivot_longer(cols = dplyr::all_of(colsSettings), names_to = "settings_name", values_to = "settings_level"),
by = c("result_id", "cdm_name", "result_type"))
colsSettings <- c("settings_name", "settings_level")
} else {
colsSettings <- character()
cli::cli_warn("There are no settings to add in the header.")
}
}
# Nice cases ----
# Get relevant columns with nice cases (body and header)
notFormat <- c("estimate_value", "cdm_name", colsGroup, colsStrata, colsAdditional, colsVariable, colsEstimate, colsSettings)
notFormat <- notFormat[(notFormat %in% colnames(x)) & (!notFormat %in% excludeColumns)]
x <- x |>
dplyr::mutate(dplyr::across(.cols = !dplyr::all_of(c("cdm_name", "estimate_name")), .fn = ~ formatString(.x))) |>
dplyr::select(!dplyr::all_of(excludeColumns)) |>
dplyr::rename_with(
.fn = ~ formatString(.x),
.cols = !dplyr::all_of(notFormat)
)
if (!"cdm_name" %in% header & !"cdm_name" %in% excludeColumns) {
x <- x |> dplyr::rename("CDM name" = "cdm_name")
}
# Header ----
# Format header
formatHeader <- character()
for (k in seq(header)) {
formatHeader <- c(formatHeader,
switch(
header[k],
"cdm_name" = c("CDM name", "cdm_name"),
"group" = colsGroup,
"strata" = colsStrata,
"additional" = colsAdditional,
"estimate" = colsEstimate,
"variable" = colsVariable,
"settings" = colsSettings,
)
)
}
if (length(formatHeader) > 0) {
x <- x |>
visOmopResults::formatHeader(
header = formatHeader,
delim = .options$delim,
includeHeaderName = FALSE,
includeHeaderKey = .options$includeHeaderKey
)
} else {
x <- x |> dplyr::rename("Estimate value" = "estimate_value")
}
# Format table ----
if (all(.options$colsToMergeRows %in% colnames(x))) {
.options$colsToMergeRows <- formatString(.options$colsToMergeRows)
}
if (!is.null(groupColumn)) {
if (groupColumn == "cdm_name") {
groupColumn <- "CDM name"
} else {
groupColumn <- formatString(groupColumn)
}
if (!groupColumn %in% colnames(x)) {
possibleGroups <- colnames(x)
possibleGroups <- gsub(" ", "_", tolower(possibleGroups[!grepl("\\[header", possibleGroups)]))
cli::cli_abort(c(paste0(
"'", groupColumn, "' is not a column in the formatted table created."),
"i" = paste0("Possible group columns are: '",
paste0(possibleGroups, collapse = "', '"), "'"
)))
}
}
if (type == "gt") {
x <- x |>
visOmopResults::gtTable(
delim = .options$delim,
style = .options$style,
na = .options$na,
title = .options$title,
subtitle = .options$subtitle,
caption = .options$caption,
groupNameCol = groupColumn,
groupNameAsColumn = .options$groupNameAsColumn,
groupOrder = .options$groupOrder,
colsToMergeRows = .options$colsToMergeRows
)
} else if (type == "flextable") {
x <- x |>
visOmopResults::fxTable(
delim = .options$delim,
style = .options$style,
na = .options$na,
title = .options$title,
subtitle = .options$subtitle,
caption = .options$caption,
groupNameCol = groupColumn,
groupNameAsColumn = .options$groupNameAsColumn,
groupOrder = .options$groupOrder,
colsToMergeRows = .options$colsToMergeRows
)
} else if (type == "tibble") {
class(x) <- class(x)[!class(x) %in% c("summarised_result", "omop_result")]
}
return(x)
}
formatString <- function(x) {
stringr::str_to_sentence(gsub("_", " ", gsub("&&&", "and", x)))
}
defaultTableOptions <- function(userOptions) {
defaultOpts <- list(
decimals = c(integer = 0, percentage = 2, numeric = 2, proportion = 2),
decimalMark = ".",
bigMark = ",",
keepNotFormatted = TRUE,
useFormatOrder = TRUE,
delim = "\n",
includeHeaderKey = TRUE,
style = "default",
na = "-",
title = NULL,
subtitle = NULL,
caption = NULL,
groupNameAsColumn = FALSE,
groupOrder = NULL,
colsToMergeRows = "all_columns"
)
for (opt in names(userOptions)) {
defaultOpts[[opt]] <- userOptions[[opt]]
}
return(defaultOpts)
}
#' Additional arguments for the function formatTable
#'
#' @description
#' It provides a list of allowed inputs for .option argument in
#' formatTable and their given default value.
#'
#'
#' @return The default .options named list.
#'
#' @export
#'
#' @examples
#' {
#' optionsFormatTable()
#' }
#'
#'
optionsFormatTable <- function() {
return(defaultTableOptions(NULL))
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/formatTable.R
|
#' Creates a flextable object from a dataframe
#'
#' @param x A dataframe.
#' @param delim Delimiter.
#' @param style Named list that specifies how to style the different parts of
#' the gt table. Accepted entries are: title, subtitle, header, header_name,
#' header_level, column_name, group_label, and body. Alternatively, use
#' "default" to get visOmopResults style, or NULL for flextable style.
#' @param na How to display missing values.
#' @param title Title of the table, or NULL for no title.
#' @param subtitle Subtitle of the table, or NULL for no subtitle.
#' @param caption Caption for the table, or NULL for no caption. Text in
#' markdown formatting style (e.g. `*Your caption here*` for caption in
#' italics).
#' @param groupNameCol Column to use as group labels.
#' @param groupNameAsColumn Whether to display the group labels as a column
#' (TRUE) or rows (FALSE).
#' @param groupOrder Order in which to display group labels.
#' @param colsToMergeRows Names of the columns to merge vertically
#' when consecutive row cells have identical values. Alternatively, use
#' "all_columns" to apply this merging to all columns, or use NULL to indicate
#' no merging.
#'
#' @return A flextable object.
#'
#' @description
#' Creates a flextable object from a dataframe using a delimiter to span
#' the header, and allows to easily customise table style.
#'
#' @examples
#' mockSummarisedResult() |>
#' formatEstimateValue(decimals = c(integer = 0, numeric = 1)) |>
#' formatHeader(header = c("Study strata", "strata_name", "strata_level"),
#' includeHeaderName = FALSE) |>
#' fxTable(
#' style = "default",
#' na = "--",
#' title = "fxTable example",
#' subtitle = NULL,
#' caption = NULL,
#' groupNameCol = "group_level",
#' groupNameAsColumn = TRUE,
#' groupOrder = c("cohort1", "cohort2"),
#' colsToMergeRows = "all_columns"
#' )
#'
#' @return A flextable object.
#'
#' @export
#'
fxTable <- function(
x,
delim = "\n",
style = "default",
na = "-",
title = NULL,
subtitle = NULL,
caption = NULL,
groupNameCol = NULL,
groupNameAsColumn = FALSE,
groupOrder = NULL,
colsToMergeRows = NULL
) {
# Package checks
rlang::check_installed("flextable")
rlang::check_installed("officer")
# Input checks
assertTibble(x)
assertCharacter(delim, length = 1)
assertCharacter(na, length = 1, null = TRUE)
assertCharacter(title, length = 1, null = TRUE)
assertCharacter(subtitle, length = 1, null = TRUE)
assertCharacter(caption, length = 1, null= TRUE)
assertCharacter(groupNameCol, null = TRUE)
assertLogical(groupNameAsColumn, length = 1)
assertCharacter(groupOrder, null = TRUE)
assertCharacter(colsToMergeRows, null = TRUE)
validateColsToMergeRows(x, colsToMergeRows, groupNameCol)
style <- validateStyle(style, "fx")
if (is.null(title) & !is.null(subtitle)) {
cli::cli_abort("There must be a title for a subtitle.")
}
# Header id's
spanCols_ids <- which(grepl("\\[header\\]|\\[header_level\\]|\\[header_name\\]|\\[column_name\\]", colnames(x)))
spanners <- strsplit(colnames(x)[spanCols_ids[1]], delim) |> unlist()
header_rows <- which(grepl("\\[header\\]", spanners))
header_name_rows <- which(grepl("\\[header_name\\]", spanners))
header_level_rows <- which(grepl("\\[header_level\\]", spanners))
# Eliminate prefixes
colnames(x) <- gsub("\\[header\\]|\\[header_level\\]|\\[header_name\\]|\\[column_name\\]", "", colnames(x))
# na
if (!is.null(na)){
x <- x |>
dplyr::mutate(
dplyr::across(dplyr::where(~is.numeric(.x)), ~as.character(.x)),
dplyr::across(colnames(x), ~ dplyr::if_else(is.na(.x), na, .x))
)
}
# Flextable
if (is.null(groupNameCol)) {
flex_x <- x |> flextable::flextable() |> flextable::separate_header(split = delim)
} else {
if (!is.null(groupOrder)) {
x <-x |> dplyr::mutate(!!groupNameCol := factor(.data[[groupNameCol]], levels = groupOrder)) |>
dplyr::relocate(!!groupNameCol) |>
dplyr::arrange(.data[[groupNameCol]])
} else {
x <- x |> dplyr::mutate(!!groupNameCol := factor(.data[[groupNameCol]])) |>
dplyr::relocate(!!groupNameCol) |>
dplyr::arrange(.data[[groupNameCol]])
}
if (groupNameAsColumn) {
flex_x <- x |> flextable::flextable() |> flextable::merge_v(j = groupNameCol) |> flextable::separate_header(split = delim)
} else {
flex_x <- x |> flextable::as_grouped_data(groups = groupNameCol) |> flextable::flextable() |>
flextable::separate_header(split = delim)
flex_x <- flex_x |>
flextable::merge_h(i = which(!is.na(flex_x$body$dataset[[groupNameCol]])), part = "body")
}
}
# Headers
if (length(header_rows)>0 & "header" %in% names(style)) {
flex_x <- flex_x |>
flextable::style(part = "header", i = header_rows, j = spanCols_ids, pr_t = style$header$text,
pr_c = style$header$cell, pr_p = style$header$paragraph)
}
if (length(header_name_rows)>0 & "header_name" %in% names(style)) {
flex_x <- flex_x |>
flextable::style(part = "header", i = header_name_rows, j = spanCols_ids, pr_t = style$header_name$text,
pr_c = style$header_name$cell, pr_p = style$header_name$paragraph)
}
if (length(header_level_rows)>0 & "header_level" %in% names(style)) {
flex_x <- flex_x |>
flextable::style(part = "header", i = header_level_rows, j = spanCols_ids, pr_t = style$header_level$text,
pr_c = style$header_level$cell, pr_p = style$header_level$paragraph)
}
if ("column_name" %in% names(style)) {
flex_x <- flex_x |>
flextable::style(part = "header", j = which(! 1:ncol(x) %in% spanCols_ids),
pr_t = style$column_name$text, pr_c = style$column_name$cell, pr_p = style$column_name$paragraph)
}
# Basic default + merge columns
if (!is.null(colsToMergeRows)) { # style while merging rows
flex_x <- fxMergeRows(flex_x, colsToMergeRows, groupNameCol)
} else {
if (!is.null(groupNameCol)) { # style group different
indRowGroup <- which(!is.na(flex_x$body$dataset[[groupNameCol]]))
flex_x <- flex_x |>
flextable::border(
j = 1,
i = indRowGroup,
border = officer::fp_border(color = "gray"),
part = "body") |>
flextable::border(border = officer::fp_border(color = "gray"),
j = 2:ncol(x),
part = "body") |>
flextable::border(
j = 1,
border.left = officer::fp_border(color = "gray"),
part = "body") |>
flextable::border( # correct group level bottom
i = nrow(flex_x$body$dataset),
border.bottom = officer::fp_border(color = "gray"),
part = "body") |>
flextable::border( # correct group level right border
i = which(!is.na(flex_x$body$dataset[[groupNameCol]])),
j = 1,
border.right = officer::fp_border(color = "transparent"),
part = "body")
} else { # style body equally
flex_x <- flex_x |>
flextable::border(border = officer::fp_border(color = "gray"),
part = "body")
}
}
flex_x <- flex_x |>
flextable::border(border = officer::fp_border(color = "gray", width = 1.2),
part = "header",
i = 1:nrow(flex_x$header$dataset)) |>
flextable::align(part = "header", align = "center") |>
flextable::valign(part = "header", valign = "center") |>
flextable::align(j = spanCols_ids, part = "body", align = "right") |>
flextable::align(j = which(!1:ncol(x) %in% spanCols_ids), part = "body", align = "left")
# Other options:
# caption
if(!is.null(caption)){
flex_x <- flex_x |>
flextable::set_caption(caption = caption)
}
# title + subtitle
if(!is.null(title) & !is.null(subtitle)){
if (! "title" %in% names(style)) {
style$title <- list("text" = officer::fp_text(bold = TRUE, font.size = 13),
"paragraph" = officer::fp_par(text.align = "center"))
}
if (! "subtitle" %in% names(style)) {
style$subtitle <- list("text" = officer::fp_text(bold = TRUE, font.size = 11),
"paragraph" = officer::fp_par(text.align = "center"))
}
flex_x <- flex_x |>
flextable::add_header_lines(values = subtitle) |>
flextable::add_header_lines(values = title) |>
flextable::style(part = "header", i = 1, pr_t = style$title$text,
pr_p = style$title$paragraph, pr_c = style$title$cell) |>
flextable::style(part = "header", i = 2, pr_t = style$subtitle$text,
pr_p = style$subtitle$paragraph, pr_c = style$subtitle$cell)
}
# title
if(!is.null(title) & is.null(subtitle)){
if (! "title" %in% names(style)) {
style$title <- list("text" = officer::fp_text(bold = TRUE, font.size = 13),
"paragraph" = officer::fp_par(text.align = "center"))
}
flex_x <- flex_x |>
flextable::add_header_lines(values = title) |>
flextable::style(part = "header", i = 1, pr_t = style$title$text,
pr_p = style$title$paragraph, pr_c = style$title$cell)
}
# body
flex_x <- flex_x |>
flextable::style(part = "body", pr_t = style$body$text,
pr_p = style$body$paragraph, pr_c = style$body$cell)
# group label
if (!is.null(groupNameCol)) {
if (!groupNameAsColumn) {
flex_x <- flex_x |>
flextable::style(part = "body", i = which(!is.na(flex_x$body$dataset[[groupNameCol]])),
pr_t = style$group_label$text, pr_p = style$group_label$paragraph, pr_c = style$group_label$cell)
} else {
flex_x <- flex_x |>
flextable::style(part = "body", j = which(flex_x$body$dataset |> colnames() == groupNameCol),
pr_t = style$group_label$text, pr_p = style$group_label$paragraph, pr_c = style$group_label$cell)
}
}
return(flex_x)
}
fxStyles <- function(styleName) {
styles <- list (
"default" = list(
"header" = list(
"cell" = officer::fp_cell(background.color = "#c8c8c8"),
"text" = officer::fp_text(bold = TRUE)),
"header_name" = list(
"cell" = officer::fp_cell(background.color = "#d9d9d9"),
"text" = officer::fp_text(bold = TRUE)),
"header_level" = list(
"cell" = officer::fp_cell(background.color = "#e1e1e1"),
"text" = officer::fp_text(bold = TRUE)),
"column_name" = list(
"text" = officer::fp_text(bold = TRUE)),
"group_label" = list(
"cell" = officer::fp_cell(background.color = "#e9e9e9",
border = officer::fp_border(color = "gray")),
"text" = officer::fp_text(bold = TRUE)),
"title" = list(
"text" = officer::fp_text(bold = TRUE, font.size = 15)),
"subtitle" = list(
"text" = officer::fp_text(bold = TRUE, font.size = 12)),
"body" = list()
)
)
if (! styleName %in% names(styles)) {
warning(paste0(styleName, " does not correspon to any of our defined styles. Returning default."),
call. = FALSE)
styleName <- "default"
}
return(styles[[styleName]])
}
fxMergeRows <- function(fx_x, colsToMergeRows, groupNameCol) {
colNms <- colnames(fx_x$body$dataset)
if (colsToMergeRows[1] == "all_columns") {
if (is.null(groupNameCol)) {
colsToMergeRows <- colNms
} else {
colsToMergeRows <- colNms[!colNms %in% groupNameCol]
}
}
# sort
ind <- match(colsToMergeRows, colNms)
names(ind) <- colsToMergeRows
colsToMergeRows <- names(sort(ind))
# fill groupCol
indColGroup <- NULL
if ( !is.null(groupNameCol)) {
groupCol <- as.character(fx_x$body$dataset[[groupNameCol]])
for (k in 2:length(groupCol)){
if (is.na(groupCol[k])) {
groupCol[k] <- groupCol[k-1]
}
}
indColGroup <- which(groupNameCol %in% colNms)
indRowGroup <- which(!is.na(fx_x$body$dataset[[groupNameCol]]))
}
for (k in seq_along(colsToMergeRows)) {
if (k > 1) {
prevMerged <- mergeCol
prevId <- prevMerged == dplyr::lag(prevMerged) & prevId
} else {
prevId <- rep(TRUE, nrow(fx_x$body$dataset))
}
col <- colsToMergeRows[k]
mergeCol <- fx_x$body$dataset[[col]]
mergeCol[is.na(mergeCol)] <- "this is NA"
if (is.null(groupNameCol)) {
id <- which(mergeCol == dplyr::lag(mergeCol) & prevId)
} else {
id <- which(groupCol == dplyr::lag(groupCol) & mergeCol == dplyr::lag(mergeCol) & prevId)
}
fx_x <- fx_x |> flextable::compose(i = id, j = ind[k], flextable::as_paragraph(flextable::as_chunk("")))
fx_x <- fx_x |>
flextable::border(
i = which(!1:nrow(fx_x$body$dataset) %in% id),
j = ind[k],
border.top = officer::fp_border(color = "gray"),
part = "body")
}
# style the rest
fx_x <- fx_x |>
flextable::border(
j = which(! 1:ncol(fx_x$body$dataset) %in% c(ind, indColGroup)),
border.top = officer::fp_border(color = "gray"),
part = "body") |>
flextable::border(
j = 1:ncol(fx_x$body$dataset),
border.right = officer::fp_border(color = "gray"),
part = "body") |>
flextable::border(
j = 1,
border.left = officer::fp_border(color = "gray"),
part = "body") |>
flextable::border( # correct bottom
i = nrow(fx_x$body$dataset),
border.bottom = officer::fp_border(color = "gray"),
part = "body")
if (!is.null(groupNameCol)) {
fx_x <- fx_x |>
flextable::border(
j = indColGroup,
i = indRowGroup,
border = officer::fp_border(color = "gray"),
part = "body") |>
flextable::border(
i = which(!is.na(fx_x$body$dataset[[groupNameCol]])),
j = 1,
border.right = officer::fp_border(color = "transparent"),
part = "body")
}
return(fx_x)
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/fxTable.R
|
#' Creates a gt object from a dataframe
#'
#' @param x A dataframe.
#' @param delim Delimiter.
#' @param style Named list that specifies how to style the different parts of
#' the gt table. Accepted entries are: title, subtitle, header, header_name,
#' header_level, column_name, group_label, and body. Alternatively, use
#' "default" to get visOmopResults style, or NULL for gt style
#' @param na How to display missing values.
#' @param title Title of the table, or NULL for no title.
#' @param subtitle Subtitle of the table, or NULL for no subtitle.
#' @param caption Caption for the table, or NULL for no caption. Text in
#' markdown formatting style (e.g. `*Your caption here*` for caption in
#' italics).
#' @param groupNameCol Column to use as group labels.
#' @param groupNameAsColumn Whether to display the group labels as a column
#' (TRUE) or rows (FALSE).
#' @param groupOrder Order in which to display group labels.
#' @param colsToMergeRows Names of the columns to merge vertically
#' when consecutive row cells have identical values. Alternatively, use
#' "all_columns" to apply this merging to all columns, or use NULL to indicate
#' no merging.
#'
#' @return gt object.
#'
#' @description
#' Creates a flextable object from a dataframe using a delimiter to span
#' the header, and allows to easily customise table style.
#'
#' @examples
#' mockSummarisedResult() |>
#' formatEstimateValue(decimals = c(integer = 0, numeric = 1)) |>
#' formatHeader(header = c("Study strata", "strata_name", "strata_level"),
#' includeHeaderName = FALSE) |>
#' gtTable(
#' style = list("header" = list(
#' gt::cell_fill(color = "#d9d9d9"),
#' gt::cell_text(weight = "bold")),
#' "header_level" = list(gt::cell_fill(color = "#e1e1e1"),
#' gt::cell_text(weight = "bold")),
#' "column_name" = list(gt::cell_text(weight = "bold")),
#' "title" = list(gt::cell_text(weight = "bold"),
#' gt::cell_fill(color = "#c8c8c8")),
#' "group_label" = gt::cell_fill(color = "#e1e1e1")),
#' na = "--",
#' title = "gtTable example",
#' subtitle = NULL,
#' caption = NULL,
#' groupNameCol = "group_level",
#' groupNameAsColumn = FALSE,
#' groupOrder = c("cohort1", "cohort2"),
#' colsToMergeRows = "all_columns"
#' )
#'
#' @return A gt table.
#'
#' @export
#'
gtTable <- function(
x,
delim = "\n",
style = "default",
na = "-",
title = NULL,
subtitle = NULL,
caption = NULL,
groupNameCol = NULL,
groupNameAsColumn = FALSE,
groupOrder = NULL,
colsToMergeRows = NULL
) {
# Package checks
rlang::check_installed("gt")
# Input checks
assertTibble(x)
assertCharacter(delim, length = 1)
assertCharacter(na, length = 1, null = TRUE)
assertCharacter(title, length = 1, null = TRUE)
assertCharacter(subtitle, length = 1, null = TRUE)
assertCharacter(caption, length = 1, null= TRUE)
assertCharacter(groupNameCol, null = TRUE)
assertLogical(groupNameAsColumn, length = 1)
assertCharacter(groupOrder, null = TRUE)
assertCharacter(colsToMergeRows, null = TRUE)
validateColsToMergeRows(x, colsToMergeRows, groupNameCol)
style <- validateStyle(style, "gt")
if (is.null(title) & !is.null(subtitle)) {
cli::cli_abort("There must be a title for a subtitle.")
}
# na
if (!is.null(na)){
x <- x |>
dplyr::mutate(
dplyr::across(dplyr::where(~is.numeric(.x)), ~as.character(.x)),
dplyr::across(colnames(x), ~ dplyr::if_else(is.na(.x), na, .x))
)
}
# Spanners
if (!is.null(groupNameCol)) {
if (is.null(groupOrder)) {
x <- x |>
dplyr::mutate(!!groupNameCol := factor(.data[[groupNameCol]])) |>
dplyr::arrange_at(groupNameCol, .by_group = TRUE)
} else {
x <- x |>
dplyr::mutate(!!groupNameCol := factor(.data[[groupNameCol]], levels = groupOrder)) |>
dplyr::arrange_at(groupNameCol, .by_group = TRUE)
}
gtResult <- x |>
gt::gt(groupname_col = groupNameCol, row_group_as_column = groupNameAsColumn) |>
gt::tab_spanner_delim(delim = delim) |>
gt::row_group_order(groups = x[[groupNameCol]] |> levels())
} else {
gtResult <- x |> gt::gt() |> gt::tab_spanner_delim(delim = delim)
}
# Header style
spanner_ids <- gtResult$`_spanners`$spanner_id
style_ids <- lapply(strsplit(spanner_ids, delim), function(vect){vect[[1]]}) |> unlist()
header_id <- grepl("\\[header\\]", style_ids)
header_name_id <- grepl("\\[header_name\\]", style_ids)
header_level_id <- grepl("\\[header_level\\]", style_ids)
# column names in spanner: header_level or header?
header_level <- all(grepl("header_level", lapply(strsplit(colnames(x)[grepl(delim, colnames(x))], delim), function(x) {x[length(x)]}) |> unlist()))
if (sum(header_id) > 0 & "header" %in% names(style)) {
gtResult <- gtResult |>
gt::tab_style(
style = style$header,
locations = gt::cells_column_spanners(spanners = spanner_ids[header_id])
)
if (!header_level) {
gtResult <- gtResult |>
gt::tab_style(
style = style$header,
locations = gt::cells_column_labels(columns = which(grepl("\\[header\\]", colnames(x))))
)
}
}
if (sum(header_name_id) > 0 & "header_name" %in% names(style)) {
gtResult <- gtResult |>
gt::tab_style(
style = style$header_name,
locations = gt::cells_column_spanners(spanners = spanner_ids[header_name_id])
)
}
if (sum(header_level_id) > 0 & "header_level" %in% names(style)) {
gtResult <- gtResult |>
gt::tab_style(
style = style$header_level,
locations = gt::cells_column_spanners(spanners = spanner_ids[header_level_id])
)
if (header_level) {
gtResult <- gtResult |>
gt::tab_style(
style = style$header_level,
locations = gt::cells_column_labels(columns = which(grepl("\\[header_level\\]", colnames(x))))
)
}
}
if ("column_name" %in% names(style)) {
col_name_ids <- which(!grepl("\\[header\\]|\\[header_level\\]|\\[header_name\\]", colnames(x)))
gtResult <- gtResult |>
gt::tab_style(
style = style$column_name,
locations = gt::cells_column_labels(columns = col_name_ids)
)
}
# Eliminate prefixes
gtResult$`_spanners`$spanner_label <- lapply(gtResult$`_spanners`$spanner_label,
function(label){
gsub("\\[header\\]|\\[header_level\\]|\\[header_name\\]|\\[column_name\\]", "", label)
})
gtResult <- gtResult |> gt::cols_label_with(columns = tidyr::contains("header"),
fn = ~ gsub("\\[header\\]|\\[header_level\\]", "", .))
# Our default:
gtResult <- gtResult |>
gt::tab_style(
style = gt::cell_text(align = "right"),
locations = gt::cells_body(columns = which(grepl("\\[header\\]|\\[header_level\\]|\\[header_name\\]|\\[column_name\\]", colnames(x))))
) |>
gt::tab_style(
style = gt::cell_text(align = "left"),
locations = gt::cells_body(columns = which(!grepl("\\[header\\]|\\[header_level\\]|\\[header_name\\]|\\[column_name\\]", colnames(x))))
) |>
gt::tab_style(
style = list(gt::cell_borders(color = "#D3D3D3")),
locations = list(gt::cells_body(columns = 2:(ncol(x)-1)))
)
# Merge rows
if (!is.null(colsToMergeRows)) {
gtResult <- gtMergeRows(gtResult, colsToMergeRows, groupNameCol, groupOrder)
}
# Other options:
## na
# if (!is.null(na)){
# # gtResult <- gtResult |> gt::sub_missing(missing_text = na)
# }
## caption
if(!is.null(caption)){
gtResult <- gtResult |>
gt::tab_caption(
caption = gt::md(caption)
)
}
## title + subtitle
if(!is.null(title) & !is.null(subtitle)){
gtResult <- gtResult |>
gt::tab_header(
title = title,
subtitle = subtitle
)
if ("title" %in% names(style)) {
gtResult <- gtResult |>
gt::tab_style(
style = style$title,
locations = gt::cells_title(groups = "title")
)
}
if ("subtitle" %in% names(style)) {
gtResult <- gtResult |>
gt::tab_style(
style = style$subtitle,
locations = gt::cells_title(groups = "subtitle")
)
}
}
## title
if(!is.null(title) & is.null(subtitle)){
gtResult <- gtResult |>
gt::tab_header(
title = title
)
if ("title" %in% names(style)) {
gtResult <- gtResult |>
gt::tab_style(
style = style$title,
locations = gt::cells_title(groups = "title")
)
}
}
## body
if ("body" %in% names(style)) {
gtResult <- gtResult |>
gt::tab_style(
style = style$body,
locations = gt::cells_body()
)
}
## group_label
if ("group_label" %in% names(style)) {
gtResult <- gtResult |>
gt::tab_style(
style = style$group_label,
locations = gt::cells_row_groups()
)
}
return(gtResult)
}
gtStyles <- function(styleName) {
styles <- list (
"default" = list(
"header" = list(gt::cell_fill(color = "#c8c8c8"),
gt::cell_text(weight = "bold", align = "center")),
"header_name" = list(gt::cell_fill(color = "#d9d9d9"),
gt::cell_text(weight = "bold", align = "center")),
"header_level" = list(gt::cell_fill(color = "#e1e1e1"),
gt::cell_text(weight = "bold", align = "center")),
"column_name" = list(gt::cell_text(weight = "bold", align = "center")),
"group_label" = list(gt::cell_fill(color = "#e9e9e9"),
gt::cell_text(weight = "bold")),
"title" = list(gt::cell_text(weight = "bold", size = 15, align = "center")),
"subtitle" = list(gt::cell_text(weight = "bold", size = 12, align = "center")),
"body" = list()
)
)
if (! styleName %in% names(styles)) {
warning(paste0(styleName, "does not correspon to any of our defined styles. Returning default."),
call. = FALSE)
styleName <- "default"
}
return(styles[[styleName]])
}
gtMergeRows <- function(gt_x, colsToMergeRows, groupNameCol, groupOrder) {
colNms <- colnames(gt_x$`_data`)
if (colsToMergeRows[1] == "all_columns") {
if (is.null(groupNameCol)) {
colsToMergeRows <- colNms
} else {
colsToMergeRows <- colNms[!colNms %in% groupNameCol]
}
}
# sort
ind <- match(colsToMergeRows, colNms)
names(ind) <- colsToMergeRows
colsToMergeRows <- names(sort(ind))
for (k in seq_along(colsToMergeRows)) {
if (k > 1) {
prevMerged <- mergeCol
prevId <- prevMerged == dplyr::lag(prevMerged) & prevId
} else {
prevId <- rep(TRUE, nrow(gt_x$`_data`))
}
col <- colsToMergeRows[k]
mergeCol <- gt_x$`_data`[[col]]
mergeCol[is.na(mergeCol)] <- "-"
if (is.null(groupNameCol)) {
id <- which(mergeCol == dplyr::lag(mergeCol) & prevId)
} else {
groupCol <- gt_x$`_data`[[groupNameCol]]
id <- which(groupCol == dplyr::lag(groupCol) & mergeCol == dplyr::lag(mergeCol) & prevId)
}
gt_x$`_data`[[col]][id] <- ""
gt_x <- gt_x |>
gt::tab_style(
style = list(gt::cell_borders(style = "hidden", sides = "top")),
locations = list(gt::cells_body(columns = col, rows = id))
)
}
return(gt_x)
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/gtTable.R
|
#' A summarised_result object filled with mock data
#'
#' @return An object of the class summarised_result with mock data.
#' @description Creates an object of the class summarised_result with mock data
#' for illustration purposes.
#'
#' @export
#'
#' @examples
#' mockSummarisedResult()
#'
#'
mockSummarisedResult <- function() {
# TO modify when PatientProfiles works with omopgenerics
# number subjects
dplyr::tibble(
"cdm_name" = "mock",
"result_type" = "mock_summarised_result",
"package_name" = "visOmopResults",
"package_version" = utils::packageVersion("visOmopResults") |>
as.character(),
"group_name" = "cohort_name",
"group_level" = c(rep("cohort1", 9), rep("cohort2", 9)),
"strata_name" = rep(c(
"overall", rep("age_group &&& sex", 4), rep("sex", 2), rep("age_group", 2)
), 2),
"strata_level" = rep(c(
"overall", "<40 &&& Male", ">=40 &&& Male", "<40 &&& Female",
">=40 &&& Female", "Male", "Female", "<40", ">=40"
), 2),
"variable_name" = "number subjects",
"variable_level" = NA_character_,
"estimate_name" = "count",
"estimate_type" = "integer",
"estimate_value" = round(10000000*stats::runif(18)) |> as.character(),
"additional_name" = "overall",
"additional_level" = "overall"
) |>
# age - mean
dplyr::union_all(
dplyr::tibble(
"cdm_name" = "mock",
"result_type" = "mock_summarised_result",
"package_name" = "visOmopResults",
"package_version" = utils::packageVersion("visOmopResults") |>
as.character(),
"group_name" = "cohort_name",
"group_level" = c(rep("cohort1", 9), rep("cohort2", 9)),
"strata_name" = rep(c(
"overall", rep("age_group &&& sex", 4), rep("sex", 2), rep("age_group", 2)
), 2),
"strata_level" = rep(c(
"overall", "<40 &&& Male", ">=40 &&& Male", "<40 &&& Female",
">=40 &&& Female", "Male", "Female", "<40", ">=40"
), 2),
"variable_name" = "age",
"variable_level" = NA_character_,
"estimate_name" = "mean",
"estimate_type" = "numeric",
"estimate_value" = c(100*stats::runif(18)) |> as.character(),
"additional_name" = "overall",
"additional_level" = "overall"
)
)|>
# age - standard deviation
dplyr::union_all(
dplyr::tibble(
"cdm_name" = "mock",
"result_type" = "mock_summarised_result",
"package_name" = "visOmopResults",
"package_version" = utils::packageVersion("visOmopResults") |>
as.character(),
"group_name" = "cohort_name",
"group_level" = c(rep("cohort1", 9), rep("cohort2", 9)),
"strata_name" = rep(c(
"overall", rep("age_group &&& sex", 4), rep("sex", 2), rep("age_group", 2)
), 2),
"strata_level" = rep(c(
"overall", "<40 &&& Male", ">=40 &&& Male", "<40 &&& Female",
">=40 &&& Female", "Male", "Female", "<40", ">=40"
), 2),
"variable_name" = "age",
"variable_level" = NA_character_,
"estimate_name" = "sd",
"estimate_type" = "numeric",
"estimate_value" = c(10*stats::runif(18)) |> as.character(),
"additional_name" = "overall",
"additional_level" = "overall"
)
) |>
# medication - count
dplyr::union_all(
dplyr::tibble(
"cdm_name" = "mock",
"result_type" = "mock_summarised_result",
"package_name" = "visOmopResults",
"package_version" = utils::packageVersion("visOmopResults") |>
as.character(),
"group_name" = "cohort_name",
"group_level" = c(rep("cohort1", 9), rep("cohort2", 9)),
"strata_name" = rep(c(
"overall", rep("age_group &&& sex", 4), rep("sex", 2), rep("age_group", 2)
), 2),
"strata_level" = rep(c(
"overall", "<40 &&& Male", ">=40 &&& Male", "<40 &&& Female",
">=40 &&& Female", "Male", "Female", "<40", ">=40"
), 2),
"variable_name" = "Medications",
"variable_level" = "Amoxiciline",
"estimate_name" = "count",
"estimate_type" = "integer",
"estimate_value" = round(100000*stats::runif(18)) |> as.character(),
"additional_name" = "overall",
"additional_level" = "overall"
)
) |>
# medication - percentage
dplyr::union_all(
dplyr::tibble(
"cdm_name" = "mock",
"result_type" = "mock_summarised_result",
"package_name" = "visOmopResults",
"package_version" = utils::packageVersion("visOmopResults") |>
as.character(),
"group_name" = "cohort_name",
"group_level" = c(rep("cohort1", 9), rep("cohort2", 9)),
"strata_name" = rep(c(
"overall", rep("age_group &&& sex", 4), rep("sex", 2), rep("age_group", 2)
), 2),
"strata_level" = rep(c(
"overall", "<40 &&& Male", ">=40 &&& Male", "<40 &&& Female",
">=40 &&& Female", "Male", "Female", "<40", ">=40"
), 2),
"variable_name" = "Medications",
"variable_level" = "Amoxiciline",
"estimate_name" = "percentage",
"estimate_type" = "percentage",
"estimate_value" = c(100*stats::runif(18)) |> as.character(),
"additional_name" = "overall",
"additional_level" = "overall"
)
) |>
# medication - count
dplyr::union_all(
dplyr::tibble(
"cdm_name" = "mock",
"result_type" = "mock_summarised_result",
"package_name" = "visOmopResults",
"package_version" = utils::packageVersion("visOmopResults") |>
as.character(),
"group_name" = "cohort_name",
"group_level" = c(rep("cohort1", 9), rep("cohort2", 9)),
"strata_name" = rep(c(
"overall", rep("age_group &&& sex", 4), rep("sex", 2), rep("age_group", 2)
), 2),
"strata_level" = rep(c(
"overall", "<40 &&& Male", ">=40 &&& Male", "<40 &&& Female",
">=40 &&& Female", "Male", "Female", "<40", ">=40"
), 2),
"variable_name" = "Medications",
"variable_level" = "Ibuprofen",
"estimate_name" = "count",
"estimate_type" = "integer",
"estimate_value" = round(100000*stats::runif(18)) |> as.character(),
"additional_name" = "overall",
"additional_level" = "overall"
)
) |>
# medication - percentage
dplyr::union_all(
dplyr::tibble(
"cdm_name" = "mock",
"result_type" = "mock_summarised_result",
"package_name" = "visOmopResults",
"package_version" = utils::packageVersion("visOmopResults") |>
as.character(),
"group_name" = "cohort_name",
"group_level" = c(rep("cohort1", 9), rep("cohort2", 9)),
"strata_name" = rep(c(
"overall", rep("age_group &&& sex", 4), rep("sex", 2), rep("age_group", 2)
), 2),
"strata_level" = rep(c(
"overall", "<40 &&& Male", ">=40 &&& Male", "<40 &&& Female",
">=40 &&& Female", "Male", "Female", "<40", ">=40"
), 2),
"variable_name" = "Medications",
"variable_level" = "Ibuprofen",
"estimate_name" = "percentage",
"estimate_type" = "percentage",
"estimate_value" = c(100*stats::runif(18)) |> as.character(),
"additional_name" = "overall",
"additional_level" = "overall"
)
) |>
# # settings
# dplyr::union_all(
# dplyr::tibble(
# "cdm_name" = "mock",
# "result_type" = "mock_summarised_result",
# "package_name" = "visOmopResults",
# "package_version" = utils::packageVersion("visOmopResults") |>
# as.character(),
# "group_name" = "overall",
# "group_level" = "overall",
# "strata_name" = "overall",
# "strata_level" = "overall",
# "variable_name" = "settings",
# "variable_level" = NA_character_,
# "estimate_name" = "mock_default",
# "estimate_type" = "logical",
# "estimate_value" = "TRUE",
# "additional_name" = "overall",
# "additional_level" = "overall"
# )
# ) |>
dplyr::mutate(result_id = as.integer(1)) |>
omopgenerics::newSummarisedResult()
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/mockResults.R
|
#' @importFrom generics tidy
#' @export
generics::tidy
#' @importFrom omopgenerics settings
#' @export
omopgenerics::settings
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/reexports.R
|
#' Split group_name and group_level columns
#'
#' @param result A dataframe with at least the columns group_name and
#' group_level.
#' @param keep Whether to keep the original group_name and group_level columns.
#' @param fill Optionally, a character that specifies what value should be
#' filled in with when missing.
#' @param overall deprecated.
#'
#' @return A dataframe.
#' @description
#' Pivots the input dataframe so the values of the column group_name are
#' transformed into columns that contain values from the group_level column.
#'
#'
#' @export
#'
#' @examples
#' mockSummarisedResult() |>
#' splitGroup()
#'
splitGroup <- function(result,
keep = FALSE,
fill = "overall",
overall = lifecycle::deprecated()) {
if (lifecycle::is_present(overall)) {
lifecycle::deprecate_warn("0.1.0", "splitGroup(overall)")
}
splitNameLevel(
result = result,
name = "group_name",
level = "group_level",
keep = keep,
fill = fill
)
}
#' Split strata_name and strata_level columns
#'
#' @param result A dataframe with at least the columns strata_name and
#' strata_level.
#' @param keep Whether to keep the original group_name and group_level columns.
#' @param fill Optionally, a character that specifies what value should be
#' filled in with when missing.
#' @param overall deprecated.
#'
#' @return A dataframe.
#' @description
#' Pivots the input dataframe so the values of the column strata_name are
#' transformed into columns that contain values from the strata_level column.
#'
#' @export
#'
#' @examples
#' mockSummarisedResult() |>
#' splitStrata()
#'
splitStrata <- function(result,
keep = FALSE,
fill = "overall",
overall = lifecycle::deprecated()) {
if (lifecycle::is_present(overall)) {
lifecycle::deprecate_warn("0.1.0", "splitStrata(overall)")
}
splitNameLevel(
result = result,
name = "strata_name",
level = "strata_level",
keep = keep,
fill = fill
)
}
#' Split additional_name and additional_level columns
#'
#' @param result A dataframe with at least the columns additional_name and
#' additional_level.
#' @param keep Whether to keep the original group_name and group_level columns.
#' @param fill Optionally, a character that specifies what value should be
#' filled in with when missing.
#' @param overall deprecated.
#'
#' @return A dataframe.
#' @description
#' Pivots the input dataframe so the values of the column additional_name are
#' transformed into columns that contain values from the additional_level column.
#'
#' @export
#'
#' @examples
#' mockSummarisedResult() |>
#' splitAdditional()
#'
splitAdditional <- function(result,
keep = FALSE,
fill = "overall",
overall = lifecycle::deprecated()) {
if (lifecycle::is_present(overall)) {
lifecycle::deprecate_warn("0.1.0", "splitAdditional(overall)")
}
splitNameLevel(
result = result,
name = "additional_name",
level = "additional_level",
keep = keep,
fill = fill
)
}
#' Split group, strata and additional at once.
#'
#' @param result A summarised_result object.
#' @param keep Whether to keep the original group_name and group_level columns.
#' @param fill Optionally, a character that specifies what value should be
#' filled in with when missing.
#' @param overall deprecated.
#'
#' @return A dataframe with group, strata and additional name as columns.
#'
#' @description
#' Pivots the input dataframe so group, strata and additional name columns are
#' transformed into columns that contain values from the corresponding level
#' columns (group, strata, and additional).
#'
#' @export
#'
#' @examples
#' mockSummarisedResult() |>
#' splitAll()
#'
splitAll <- function(result,
keep = FALSE,
fill = "overall",
overall = lifecycle::deprecated()) {
if (lifecycle::is_present(overall)) {
lifecycle::deprecate_warn("0.1.0", "splitAll(overall)")
}
result |>
splitGroup(keep = keep, fill = fill) |>
splitStrata(keep = keep, fill = fill) |>
splitAdditional(keep = keep, fill = fill)
}
#' Split name and level columns into the columns
#'
#' @param result A summarised_result object.
#' @param name Column with the names.
#' @param level Column with the levels.
#' @param keep Whether to keep the original group_name and group_level columns.
#' @param fill Optionally, a character that specifies what value should be
#' filled in with when missing.
#' @param overall deprecated.
#'
#' @return A dataframe with the specified name column values as columns.
#' @description
#' Pivots the input dataframe so the values of the name columns are transformed
#' into columns, which values come from the specified level column.
#'
#' @export
#'
#' @examples
#' mockSummarisedResult() |>
#' splitNameLevel(name = "group_name",
#' level = "group_level",
#' keep = FALSE)
#'
splitNameLevel <- function(result,
name = "group_name",
level = "group_level",
keep = FALSE,
fill = "overall",
overall = lifecycle::deprecated()) {
if (lifecycle::is_present(overall)) {
lifecycle::deprecate_warn("0.1.0", "splitNameLevel(overall)")
}
assertCharacter(name, length = 1)
assertCharacter(level, length = 1)
assertLogical(keep, length = 1)
assertTibble(result, columns = c(name, level))
assertCharacter(fill, length = 1, na = TRUE)
newCols <- getColumns(result = result, col = name)
id <- which(name == colnames(result))
nameValues <- result[[name]] |> strsplit(" and | &&& ")
levelValues <- result[[level]] |> strsplit(" and | &&& ")
if (!all(lengths(nameValues) == lengths(levelValues))) {
cli::cli_abort("Column names and levels number does not match")
}
present <- newCols[newCols %in% colnames(result)]
if (length(present) > 0) {
cli::cli_warn(
"The following columns will be overwritten:
{paste0(present, collapse = ', ')}."
)
}
for (k in seq_along(newCols)) {
col <- newCols[k]
dat <- lapply(seq_along(nameValues), function(y) {
res <- levelValues[[y]][nameValues[[y]] == col]
if (length(res) == 0) {
return(as.character(NA))
} else {
return(res)
}
}) |>
unlist()
result[[col]] <- dat
}
if (!keep) {
result <- result |> dplyr::select(-dplyr::all_of(c(name, level)))
colskeep <- character()
} else {
colskeep <- c(name, level)
}
# move cols
if (id == 1) {
result <- result |> dplyr::relocate(dplyr::any_of(newCols))
} else {
id <- colnames(result)[id - 1]
result <- result |>
dplyr::relocate(
dplyr::any_of(c(colskeep, newCols)), .after = dplyr::all_of(id)
)
}
# use fill
if (!is.na(fill)) {
result <- result |>
dplyr::mutate(dplyr::across(
dplyr::any_of(newCols),
~ dplyr::if_else(is.na(.x), .env$fill, .x)
))
}
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/split.R
|
#' Get a tidy visualization of a summarised_result object
#'
#' @param x A summarised_result.
#' @param splitGroup If TRUE it will split the group name-level column pair.
#' @param splitStrata If TRUE it will split the group name-level column pair.
#' @param splitAdditional If TRUE it will split the group name-level column pair.
#' @param pivotEstimatesBy Names from which pivot wider the estimate values. If
#' NULL the table will not be pivotted.
#' @param nameStyle Name style (glue package specifications) to customize names
#' when pivotting estimates. If NULL standard tidyr::pivot_wider formatting will
#' be used.
#' @param ... For compatibility (not used).
#'
#' @return A tibble.
#'
#' @description
#' `r lifecycle::badge("experimental")`
#' Provides tools for obtaining a tidy version of a summarised_result object. If
#' the summarised results object contains settings, these will be transformed
#' into columns.
#'
#' @export
#'
#' @examples
#' result <- mockSummarisedResult()
#'
#' result |> tidy()
#'
tidy.summarised_result <- function(x,
splitGroup = TRUE,
splitStrata = TRUE,
splitAdditional = TRUE,
pivotEstimatesBy = "estimate_name",
nameStyle = NULL,
...) {
# initial checks
assertTibble(x, columns = pivotEstimatesBy)
assertLogical(splitGroup, length = 1)
assertLogical(splitStrata, length = 1)
assertLogical(splitAdditional, length = 1)
assertCharacter(pivotEstimatesBy, null = TRUE)
assertCharacter(nameStyle, null = TRUE)
# code
result_out <- x |>
dplyr::filter(.data$variable_name != "settings")
if (splitGroup) {
result_out <- result_out |> splitGroup()
}
if (splitStrata) {
result_out <- result_out |> splitStrata()
}
if (splitAdditional) {
result_out <- result_out |> splitAdditional()
}
if (length(pivotEstimatesBy) > 0) {
if (is.null(nameStyle)) {
nameStyle <- paste0("{", paste0(pivotEstimatesBy, collapse = "}_{"), "}")
}
typeNameConvert <- result_out |>
dplyr::distinct(dplyr::across(dplyr::all_of(c("estimate_type", pivotEstimatesBy)))) |>
dplyr::mutate(estimate_type = dplyr::case_when(
grepl("percentage|proportion", .data$estimate_name) ~ "numeric",
!grepl("numeric|percentage|proportion|integer|date|double|logical|character", .data$estimate_type) ~ "character",
.default = .data$estimate_type
),
new_name = glue::glue(nameStyle)
)
result_out <- result_out |>
dplyr::select(-"estimate_type") |>
tidyr::pivot_wider(
names_from = dplyr::all_of(pivotEstimatesBy),
values_from = "estimate_value",
names_glue = nameStyle
) |>
dplyr::mutate(
dplyr::across(dplyr::all_of(typeNameConvert$new_name),
~ asEstimateType(.x, name = deparse(substitute(.)), dict = typeNameConvert)
)
)
}
settings <- x |> omopgenerics::settings()
if (nrow(settings) > 0) {
result_out <- result_out |>
dplyr::left_join(settings,
by = c("result_id", "cdm_name", "result_type"))
}
return(result_out)
}
asEstimateType <- function(x, name, dict) {
type <- dict$estimate_type[dict$new_name == name]
return(eval(parse(text = paste0("as.", type, "(x)"))))
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/tidy.R
|
#' Unite one or more columns in name-level format
#'
#' @param x A dataframe.
#' @param cols Columns to aggregate.
#' @param name Column name of the `name` column.
#' @param level Column name of the `level` column.
#' @param keep Whether to keep the original columns.
#' @param ignore Level values to ignore.
#'
#' @return A tibble with the new columns.
#' @description
#' Unites targeted table columns into a pair of name-level columns.
#'
#'
#' @examples
#' x <- dplyr::tibble(
#' variable = "number subjects",
#' value = c(10, 15, 40, 78),
#' sex = c("Male", "Female", "Male", "Female"),
#' age_group = c("<40", ">40", ">40", "<40")
#' )
#'
#' x |>
#' uniteNameLevel(
#' cols = c("sex", "age_group"),
#' name = "new_column_name",
#' level = "new_column_level"
#' )
#'
#' @export
#'
uniteNameLevel <- function(x,
cols = character(0),
name = "group_name",
level = "group_level",
keep = FALSE,
ignore = c(NA, "overall")) {
# initial checks
assertCharacter(cols)
assertCharacter(name, length = 1)
assertCharacter(level, length = 1)
assertLogical(keep, length = 1)
assertCharacter(ignore, na = TRUE)
assertTibble(x, columns = cols)
if (name == level) {
cli::cli_abort("Provide different names for the name and level columns.")
}
if (length(cols) > 0) {
id <- min(which(colnames(x) %in% cols))
present <- c(name, level)[c(name, level) %in% colnames(x)]
if (length(present) > 0) {
cli::cli_warn(
"The following columns will be overwritten:
{paste0(present, collapse = ', ')}."
)
}
keyWord <- " &&& "
containKey <- cols[grepl(keyWord, cols)]
if (length(containKey) > 0) {
cli::cli_abort("Column names must not contain '{keyWord}' : `{paste0(containKey, collapse = '`, `')}`")
}
containKey <- cols[
lapply(cols, function(col){any(grepl(keyWord, x[[col]]))}) |> unlist()
]
if (length(containKey) > 0) {
cli::cli_abort("Column values must not contain '{keyWord}'. Present in: `{paste0(containKey, collapse = '`, `')}`.")
}
x <- x |>
newNameLevel(
cols = cols, name = name, level = level, ignore = ignore,
keyWord = keyWord
)
if (keep) {
colskeep <- cols
} else {
colskeep <- character()
x <- x |> dplyr::select(!dplyr::all_of(cols))
}
# move cols
if (id == 1) {
x <- x |>
dplyr::relocate(dplyr::all_of(c(colskeep, name, level)))
} else {
id <- colnames(x)[id - 1]
x <- x |>
dplyr::relocate(
dplyr::all_of(c(colskeep, name, level)), .after = dplyr::all_of(id)
)
}
} else {
x <- x |>
dplyr::mutate(!!name := "overall", !!level := "overall")
}
return(x)
}
#' Unite one or more columns in group_name-group_level format
#'
#' @param x Tibble or dataframe.
#' @param cols Columns to aggregate.
#' @param keep Whether to keep the original columns.
#' @param ignore Level values to ignore.
#'
#' @return A tibble with the new columns.
#' @description
#' Unites targeted table columns into group_name-group_level columns.
#'
#' @examples
#' x <- dplyr::tibble(
#' variable = "number subjects",
#' value = c(10, 15, 40, 78),
#' sex = c("Male", "Female", "Male", "Female"),
#' age_group = c("<40", ">40", ">40", "<40")
#' )
#'
#' x |>
#' uniteGroup(c("sex", "age_group"))
#'
#' @export
#'
uniteGroup <- function(x,
cols,
keep = FALSE,
ignore = c(NA, "overall")) {
uniteNameLevel(
x = x, cols = cols, name = "group_name", level = "group_level", keep = keep,
ignore = ignore
)
}
#' Unite one or more columns in strata_name-strata_level format
#'
#' @param x Tibble or dataframe.
#' @param cols Columns to aggregate.
#' @param keep Whether to keep the original columns.
#' @param ignore Level values to ignore.
#'
#' @return A tibble with the new columns.
#' @description
#' Unites targeted table columns into strata_name-strata_level columns.
#'
#' @examples
#' x <- dplyr::tibble(
#' variable = "number subjects",
#' value = c(10, 15, 40, 78),
#' sex = c("Male", "Female", "Male", "Female"),
#' age_group = c("<40", ">40", ">40", "<40")
#' )
#'
#' x |>
#' uniteStrata(c("sex", "age_group"))
#'
#' @export
#'
uniteStrata <- function(x,
cols,
keep = FALSE,
ignore = c(NA, "overall")) {
uniteNameLevel(
x = x, cols = cols, name = "strata_name", level = "strata_level",
keep = keep, ignore = ignore
)
}
#' Unite one or more columns in additional_name-additional_level format
#'
#' @param x Tibble or dataframe.
#' @param cols Columns to aggregate.
#' @param keep Whether to keep the original columns.
#' @param ignore Level values to ignore.
#'
#' @return A tibble with the new columns.
#' @description
#' Unites targeted table columns into additional_name-additional_level columns.
#'
#' @examples
#' x <- dplyr::tibble(
#' variable = "number subjects",
#' value = c(10, 15, 40, 78),
#' sex = c("Male", "Female", "Male", "Female"),
#' age_group = c("<40", ">40", ">40", "<40")
#' )
#'
#' x |>
#' uniteAdditional(c("sex", "age_group"))
#'
#' @export
#'
uniteAdditional <- function(x,
cols,
keep = FALSE,
ignore = c(NA, "overall")) {
uniteNameLevel(
x = x, cols = cols, name = "additional_name", level = "additional_level",
keep = keep, ignore = ignore
)
}
## Helpers ---
newNameLevel <- function(x, cols, name, level, ignore, keyWord) {
y <- x |>
dplyr::select(dplyr::all_of(cols)) |>
dplyr::distinct()
nms <- character(nrow(y))
lvl <- character(nrow(y))
for (k in seq_len(nrow(y))) {
lev <- y[k, ] |> as.matrix() |> as.vector()
ind <- which(!lev %in% ignore)
if (length(ind) > 0) {
nms[k] <- paste0(cols[ind], collapse = keyWord)
lvl[k] <- paste0(lev[ind], collapse = keyWord)
} else {
nms[k] <- "overall"
lvl[k] <- "overall"
}
}
x <- x |>
dplyr::inner_join(
y |>
dplyr::mutate(!!name := .env$nms, !!level := .env$lvl),
na_matches = "na",
by = cols
)
return(x)
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/unite.R
|
validateResult <- function(x, call = parent.frame()) {
xn <- tryCatch(
omopgenerics::newSummarisedResult(x),
error = function(e){NULL}
)
if (!is.null(xn)) {
return(xn)
}
if (!is.null(xn)) {
return(xn)
}
cli::cli_abort("Please provide a valid result object.", call = call)
}
validateDecimals <- function(result, decimals) {
nm_type <- omopgenerics::estimateTypeChoices()
nm_name <- result[["estimate_name"]] |> unique()
errorMesssage <- "`decimals` must be named integerish vector. Names refere to estimate_type or estimate_name values."
if (is.null(decimals)) {
} else if (any(is.na(decimals))) { # NA
cli::cli_abort(errorMesssage)
} else if (!is.numeric(decimals)) { # not numeric
cli::cli_abort(errorMesssage)
} else if (!all(decimals == floor(decimals))) { # not integer
cli::cli_abort(errorMesssage)
} else if (!all(names(decimals) %in% c(nm_type, nm_name))) { # not correctly named
conflict_nms <- names(decimals)[!names(decimals) %in% c(nm_type, nm_name)]
cli::cli_abort(paste0(paste0(conflict_nms, collapse = ", "), " do not correspont to estimate_type or estimate_name values."))
} else if (length(decimals) == 1 & is.null(names(decimals))) { # same number to all
decimals <- rep(decimals, length(nm_type))
names(decimals) <- nm_type
} else {
decimals <- c(decimals[names(decimals) %in% nm_name],
decimals[names(decimals) %in% nm_type])
}
return(decimals)
}
validateEstimateNameFormat <- function(format, call = parent.frame()) {
if (!is.null(format)) {
if (length(format) > 0){
if (length(regmatches(format, gregexpr("(?<=\\<).+?(?=\\>)", format, perl = T)) |> unlist()) == 0) {
cli::cli_abort("format input does not contain any estimate name indicated by <...>.")
}
} else {
format <- NULL
}
}
return(format)
}
validateStyle <- function(style, tableFormatType) {
if (is.list(style) | is.null(style)) {
assertList(style, null = TRUE, named = TRUE)
} else if (is.character(style)) {
assertCharacter(style, null = TRUE)
eval(parse(text = paste0("style <- ", tableFormatType, "Styles(styleName = style)")))
} else {
if (tableFormatType == "fx") {
tableFormatType <- "flextable"
}
cli::cli_abort(paste0("Style must be one of 1) a named list of ", tableFormatType, " styling functions,
2) the string 'default' for visOmopResults default style, or 3) NULL to indicate no styling."))
}
return(style)
}
validateColsToMergeRows <- function(x, colsToMergeRows, groupNameCol) {
if (!is.null(colsToMergeRows)) {
if (any(colsToMergeRows %in% groupNameCol)) {
cli::cli_abort("groupNameCol and colsToMergeRows must have different column names.")
}
ind <- ! colsToMergeRows %in% c(colnames(x), "all_columns")
if (sum(ind) == 1) {
warning(paste0(colsToMergeRows[ind], " is not a column in the dataframe."))
} else if (sum(ind) > 1) {
warning(paste0(colsToMergeRows[ind], " are not columns in the dataframe."))
}
}
}
validateDelim <- function(delim) {
if (!rlang::is_character(delim)) {
cli::cli_abort("The value supplied for `delim` must be of type `character`.")
}
if (length(delim) != 1) {
cli::cli_abort("`delim` must be a single value.")
}
if (nchar(delim) != 1) {
cli::cli_abort("The value supplied for `delim` must be a single character.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/R/utilities.R
|
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
warning = FALSE,
message = FALSE
)
## ----setup--------------------------------------------------------------------
library(visOmopResults)
library(dplyr)
mock_sr <- mockSummarisedResult()
mock_sr |> glimpse()
## -----------------------------------------------------------------------------
mock_sr <- mock_sr |> formatEstimateValue()
mock_sr |> glimpse()
## -----------------------------------------------------------------------------
mock_sr <- mock_sr |>
formatEstimateName(
estimateNameFormat = c(
"N (%)" = "<count> (<percentage>%)",
"N" = "<count>",
"Mean (SD)" = "<mean> (<sd>)"
),
keepNotFormatted = FALSE,
useFormatOrder = FALSE
)
mock_sr |> glimpse()
## -----------------------------------------------------------------------------
mock_sr |>
formatHeader(
header = c("Names of the cohorts", "group_level"),
delim = "\n",
includeHeaderName = TRUE,
includeHeaderKey = TRUE
) |>
glimpse()
## -----------------------------------------------------------------------------
mock_sr <- mock_sr |>
mutate(across(c("strata_name", "strata_level"), ~ gsub("&&&", "and", .x))) |>
formatHeader(
header = c("Stratifications", "strata_name", "strata_level"),
delim = "\n",
includeHeaderName = FALSE,
includeHeaderKey = TRUE
)
mock_sr |> glimpse()
## -----------------------------------------------------------------------------
# first we select the columns we want:
mock_sr <- mock_sr |>
splitGroup() |>
select(!all_of(c("cdm_name", "result_type", "package_name",
"package_version", "estimate_type", "result_id",
"additional_name", "additional_level")))
mock_sr |> gtTable()
## -----------------------------------------------------------------------------
mock_sr |>
gtTable(
groupNameCol = "cohort_name",
groupNameAsColumn = FALSE,
groupOrder = c("cohort1", "cohort2"),
colsToMergeRows = "all_columns"
)
## -----------------------------------------------------------------------------
mock_sr |>
gtTable(
style = list(
"header" = list(gt::cell_text(weight = "bold"),
gt::cell_fill(color = "orange")),
"header_level" = list(gt::cell_text(weight = "bold"),
gt::cell_fill(color = "yellow")),
"column_name" = gt::cell_text(weight = "bold"),
"group_label" = list(gt::cell_fill(color = "blue"),
gt::cell_text(color = "white", weight = "bold")),
"body" = gt::cell_text(color = "red")
),
groupNameCol = "cohort_name",
groupNameAsColumn = FALSE,
groupOrder = c("cohort1", "cohort2"),
colsToMergeRows = "all_columns"
)
## -----------------------------------------------------------------------------
mock_sr |>
fxTable(
style = list(
"header" = list(
"cell" = officer::fp_cell(background.color = "orange"),
"text" = officer::fp_text(bold = TRUE)),
"header_level" = list(
"cell" = officer::fp_cell(background.color = "yellow"),
"text" = officer::fp_text(bold = TRUE)),
"column_name" = list("text" = officer::fp_text(bold = TRUE)),
"group_label" = list(
"cell" = officer::fp_cell(background.color = "blue"),
"text" = officer::fp_text(bold = TRUE, color = "white")),
"body" = list("text" = officer::fp_text(color = "red"))
),
groupNameCol = "cohort_name",
groupNameAsColumn = FALSE,
groupOrder = c("cohort1", "cohort2"),
colsToMergeRows = "all_columns"
)
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/inst/doc/formatFunctions.R
|
---
title: "format functions"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{format functions}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
warning = FALSE,
message = FALSE
)
```
The **format** set of functions can be combined to format a summarised_result object (see R package *omopgenerics*) into a nice dataframe, *flextable* or *gt* table to display. In what follows, we show the pipline for formatting summarised_results using these functions.
First, we load the relevant libraries and generate a mock summarised_result.
```{r setup}
library(visOmopResults)
library(dplyr)
mock_sr <- mockSummarisedResult()
mock_sr |> glimpse()
```
## 1. formatEstimateValue()
This function provides tools to format the estimate_value column. It allows to change the number of decimals to display by estimate_type or *estimate_name* (`decimals`), and to change the decimal and thousand/million separator mark (`decimalMark` and `bigMark` respectively). By default,
decimals of integer values are set to 0, numeric to 2, percentage to 1, and proportion to 3. The defaulted decimal mark is "." while the thousand/million separator is ",".
```{r}
mock_sr <- mock_sr |> formatEstimateValue()
mock_sr |> glimpse()
```
## 2. formatEstimateName()
This functions helps to manipulate *estimate_name* and *estimate_value* columns. For instance, if we want that all the variables for which we have counts and percentage to be display in a single row showing both as "N (%)" we can do it with this function.
The `estimateNameFormat` is where all combinations or renaming of estimates can be specified. Values from *estimate_name*'s column should be specified between <...>. The new *estimate_name* values to use will be the names of the vector, or the value itself when it is not named.
```{r}
mock_sr <- mock_sr |>
formatEstimateName(
estimateNameFormat = c(
"N (%)" = "<count> (<percentage>%)",
"N" = "<count>",
"Mean (SD)" = "<mean> (<sd>)"
),
keepNotFormatted = FALSE,
useFormatOrder = FALSE
)
mock_sr |> glimpse()
```
Additional input arguments are `keepNotFormatted` to specify whether not formatted rows should be returned or dropped, and `useFormatOrder` to define if rows should be sorted as in `estimateNameFormat` or if the original order should be kept. In the latter scenario, when more than one estimate is pulled together, the new estimate position will be the first of the estimates being merged.
## 3. formatHeader()
This function helps to create a nice header for a *flextable*, *gt* table and other table formatting packages.
To this aim, this function pivots the columns specified in `header` "widening" the table. The name of the new columns can be formatted with the arguments `header`, `delim`, `inlcudeHeaderName`, and `includeHeaderKey` to later convert obtain a nice header of the formatted table (*flextable* or *gt* table).
#### Header keys
There are 3 different types of headers, identified with the keys "header", "header_name", and "header_level".
- **header:** Header labels passed to `header` but which are not part of the input table (are not columns names or values).
- **header_name:** Header labels that come from column names in the input table.
- **header_level:** Header labels that come from values of selected columns in the input table.
For instance, we might want to pivot by "group_level" and have an upper header called "Names of the cohorts". To do that we would proceed as follows:
```{r}
mock_sr |>
formatHeader(
header = c("Names of the cohorts", "group_level"),
delim = "\n",
includeHeaderName = TRUE,
includeHeaderKey = TRUE
) |>
glimpse()
```
The labels indicating which type of header refers to in the new column names can be removed with `includeHeaderKey`. However, having these keys in our header will allow to style separately the different header types in the next step (`fxTable` and `gtTable`).
Continuing with our example, we want to pivot by strata (name and level), but, we do not want the column names to appear in the header:
```{r}
mock_sr <- mock_sr |>
mutate(across(c("strata_name", "strata_level"), ~ gsub("&&&", "and", .x))) |>
formatHeader(
header = c("Stratifications", "strata_name", "strata_level"),
delim = "\n",
includeHeaderName = FALSE,
includeHeaderKey = TRUE
)
mock_sr |> glimpse()
```
Notice, how we substitute the keyWord "&&&" to "and", to get a nice header.
## 4. gtTable() and fxTable()
Finally, we have the functions `gtTable` and `fxTable` which will transform our tibble into a *gt* or *flextable* object respectively. These functions provide several tools to personalise the formatted table.
### gtTable()
Let's start by manipulating the dataframe to have the columns that we want to display, and then use `gtTable` with default values:
```{r}
# first we select the columns we want:
mock_sr <- mock_sr |>
splitGroup() |>
select(!all_of(c("cdm_name", "result_type", "package_name",
"package_version", "estimate_type", "result_id",
"additional_name", "additional_level")))
mock_sr |> gtTable()
```
Now, we want to group results by "cohort_name". More specifically we want to have a row which the name of each cohort before the results of that cohort, and that *cohort1* comes before *cohort2*. Additionally, we want to merge those rows what contain the same information for all the columns. To get this table we will use `gtTable` as follows:
```{r}
mock_sr |>
gtTable(
groupNameCol = "cohort_name",
groupNameAsColumn = FALSE,
groupOrder = c("cohort1", "cohort2"),
colsToMergeRows = "all_columns"
)
```
We might also want to modify the default style of the table. For instance, we might want to highlight the cohort_name labels with a blue background, have the body text in red, and use a combination of orange and yellow for the header. We can do it with the `style` argument:
```{r}
mock_sr |>
gtTable(
style = list(
"header" = list(gt::cell_text(weight = "bold"),
gt::cell_fill(color = "orange")),
"header_level" = list(gt::cell_text(weight = "bold"),
gt::cell_fill(color = "yellow")),
"column_name" = gt::cell_text(weight = "bold"),
"group_label" = list(gt::cell_fill(color = "blue"),
gt::cell_text(color = "white", weight = "bold")),
"body" = gt::cell_text(color = "red")
),
groupNameCol = "cohort_name",
groupNameAsColumn = FALSE,
groupOrder = c("cohort1", "cohort2"),
colsToMergeRows = "all_columns"
)
```
### fxTable()
To obtain a similar result but with a *flextable* object, we can use `fxTable` with the same arguments as before, however, `style` must be adapted to use the *officer* package since it is the accepted by *flextable*.
```{r}
mock_sr |>
fxTable(
style = list(
"header" = list(
"cell" = officer::fp_cell(background.color = "orange"),
"text" = officer::fp_text(bold = TRUE)),
"header_level" = list(
"cell" = officer::fp_cell(background.color = "yellow"),
"text" = officer::fp_text(bold = TRUE)),
"column_name" = list("text" = officer::fp_text(bold = TRUE)),
"group_label" = list(
"cell" = officer::fp_cell(background.color = "blue"),
"text" = officer::fp_text(bold = TRUE, color = "white")),
"body" = list("text" = officer::fp_text(color = "red"))
),
groupNameCol = "cohort_name",
groupNameAsColumn = FALSE,
groupOrder = c("cohort1", "cohort2"),
colsToMergeRows = "all_columns"
)
```
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/inst/doc/formatFunctions.Rmd
|
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
warning = FALSE,
message = FALSE
)
## ----setup--------------------------------------------------------------------
library(visOmopResults)
library(dplyr)
mock_sr <- mockSummarisedResult()
mock_sr |> glimpse()
## -----------------------------------------------------------------------------
mock_sr |> splitGroup() |> glimpse()
## -----------------------------------------------------------------------------
mock_sr |> splitStrata() |> glimpse()
mock_sr |> splitAdditional() |> glimpse()
mock_sr |> splitAll() |> glimpse()
## -----------------------------------------------------------------------------
data_to_split <- tibble(
denominator = "general_population",
outcome = "stroke",
input_arguments = c("wash_out &&& previous_observation"),
input_arguments_values = c("60 &&& 180")
)
data_to_split
## -----------------------------------------------------------------------------
data_to_split |>
splitNameLevel(
name = "input_arguments",
level = "input_arguments_values"
)
## -----------------------------------------------------------------------------
to_unite_group <- tibble(
denominator_cohort_name = c("general_population", "older_than_60", "younger_than_60"),
outcome_cohort_name = c("stroke", "stroke", "stroke")
)
to_unite_group |>
uniteGroup(cols = c("denominator_cohort_name", "outcome_cohort_name"))
## -----------------------------------------------------------------------------
to_unite_strata <- tibble(
age = c(NA, ">40", "<=40", NA, NA, NA, NA, NA, ">40", "<=40"),
sex = c(NA, NA, NA, "F", "M", NA, NA, NA, "F", "M"),
region = c(NA, NA, NA, NA, NA, "North", "South", "Center", NA, NA)
)
to_unite_strata |>
uniteStrata(cols = c("age", "sex", "region"),
ignore = character())
## -----------------------------------------------------------------------------
to_unite_strata |>
uniteStrata(cols = c("age", "sex", "region"))
## -----------------------------------------------------------------------------
to_unite_strata |>
uniteNameLevel(cols = c("age", "sex", "region"),
name = "name",
level = "level",
keep = TRUE)
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/inst/doc/splitAndUnite.R
|
---
title: "split and unite functions"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{split and unite functions}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
warning = FALSE,
message = FALSE
)
```
**Split** and **unite** are complementary functions to manipulate dataframes in R. They work with summarised_results objects (see R package *omopgenerics*), but they can also support R dataframes from other classes.
## summarised_result
First, let's load relevant libraries and generate a mock summarised_result object to use in the following examples.
```{r setup}
library(visOmopResults)
library(dplyr)
mock_sr <- mockSummarisedResult()
mock_sr |> glimpse()
```
A summarised_result contains 3 types of name-level paired columns which are targeted by the set of unite and split functions. These are the **group** columns which typically can contain information about cohorts, **strata** columns which have data on stratification for each group, and finally the **additional** columns which include further information not covered by group and strata.
## Split functions
The idea of the split functions is to pivot the "name" (e.g. *group_name*) column to split each value of that column into a column in the dataframe, which values are taken by the "level" (e.g. *group_level*) column.
### splitGroup(), splitStrata(), and splitAdditional()
For instance, the `splitGroup` function will target the *group_name-group_level* columns as seen below.
```{r}
mock_sr |> splitGroup() |> glimpse()
```
Similar to `splitStrata`, the functions `splitGroup` will split *group_name* and *group_level* columns, while `splitAdditional` will split the additional name-level pair. Finally, the function `splitAll` will split group, strata, and additional at once. Note that after using `splitStrata` on our summarised_result object, we do no longer have a *strata_name-strata_level* pair, instead we have two new columns corresponding to the stratifications, *age_group* and *sex*.
```{r}
mock_sr |> splitStrata() |> glimpse()
mock_sr |> splitAdditional() |> glimpse()
mock_sr |> splitAll() |> glimpse()
```
#### !! Keyword: &&&
Looking at the results below, observe how the splitting was not only done by values in the "name" column, but also among values containing the key word "**&&&**". That is, "sex &&& age_group" was splitted into *sex* and *age_group* columns, instead of generating a column called "*sex &&& age_group*".
### splitNameLevel()
The function `splitNameLevel` provides a more tailored splitting of the dataframe. This function can take any dataframe with no restrictions to the naming of the name-level pair columns, since these can be specified in the `name` and `level` arguments.
For instance let's use it in the following table:
```{r}
data_to_split <- tibble(
denominator = "general_population",
outcome = "stroke",
input_arguments = c("wash_out &&& previous_observation"),
input_arguments_values = c("60 &&& 180")
)
data_to_split
```
```{r}
data_to_split |>
splitNameLevel(
name = "input_arguments",
level = "input_arguments_values"
)
```
The function `splitNameLevel`, in additionally to the argument `overall` previously seen, has the argument `keep` to set whether we want to keep the columns before the splitting.
## Unite functions
The unite functions are the complementary to the split ones. These are meant to generate name-level pair columns from targeted columns within a dataframe.
### uniteGroup(), uniteStrata(), and uniteAdditional()
To work with summarised_result objects, we have the `uniteGroup`, `uniteStrata`, and `uniteAdditional` functions which will generate the group, strata, and additional name-level columns respectively from a given set of columns. For instance, in the following example we want to create the *group_name* and *group_level* columns:
```{r}
to_unite_group <- tibble(
denominator_cohort_name = c("general_population", "older_than_60", "younger_than_60"),
outcome_cohort_name = c("stroke", "stroke", "stroke")
)
to_unite_group |>
uniteGroup(cols = c("denominator_cohort_name", "outcome_cohort_name"))
```
A part from the columns to unite argument (`cols`), there is the argument `ignore`, by default: `ignore = c(NA, "overall")`. This means that, levels within ignore will be ignored. For example if in this case we do not ignore them we will obtain the NA as output:
```{r}
to_unite_strata <- tibble(
age = c(NA, ">40", "<=40", NA, NA, NA, NA, NA, ">40", "<=40"),
sex = c(NA, NA, NA, "F", "M", NA, NA, NA, "F", "M"),
region = c(NA, NA, NA, NA, NA, "North", "South", "Center", NA, NA)
)
to_unite_strata |>
uniteStrata(cols = c("age", "sex", "region"),
ignore = character())
```
By default (`ignore = c(NA, "overall")`) we obtain an output where only names and levels of non-NA values are returned, and from those rows where all values are NA it uses "overall".
```{r}
to_unite_strata |>
uniteStrata(cols = c("age", "sex", "region"))
```
### uniteNameLevel()
Lastly, the function `uniteNameLevel`, idem to `splitNameLevel`, provides more flexibility on the name-level column naming, in addition of the `keep` argument (FALSE by default) to choose whether to keep the targeted columns. For instance, if we repeat the previous example with `keep` set to TRUE we would obtain the following output:
```{r}
to_unite_strata |>
uniteNameLevel(cols = c("age", "sex", "region"),
name = "name",
level = "level",
keep = TRUE)
```
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/inst/doc/splitAndUnite.Rmd
|
---
title: "format functions"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{format functions}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
warning = FALSE,
message = FALSE
)
```
The **format** set of functions can be combined to format a summarised_result object (see R package *omopgenerics*) into a nice dataframe, *flextable* or *gt* table to display. In what follows, we show the pipline for formatting summarised_results using these functions.
First, we load the relevant libraries and generate a mock summarised_result.
```{r setup}
library(visOmopResults)
library(dplyr)
mock_sr <- mockSummarisedResult()
mock_sr |> glimpse()
```
## 1. formatEstimateValue()
This function provides tools to format the estimate_value column. It allows to change the number of decimals to display by estimate_type or *estimate_name* (`decimals`), and to change the decimal and thousand/million separator mark (`decimalMark` and `bigMark` respectively). By default,
decimals of integer values are set to 0, numeric to 2, percentage to 1, and proportion to 3. The defaulted decimal mark is "." while the thousand/million separator is ",".
```{r}
mock_sr <- mock_sr |> formatEstimateValue()
mock_sr |> glimpse()
```
## 2. formatEstimateName()
This functions helps to manipulate *estimate_name* and *estimate_value* columns. For instance, if we want that all the variables for which we have counts and percentage to be display in a single row showing both as "N (%)" we can do it with this function.
The `estimateNameFormat` is where all combinations or renaming of estimates can be specified. Values from *estimate_name*'s column should be specified between <...>. The new *estimate_name* values to use will be the names of the vector, or the value itself when it is not named.
```{r}
mock_sr <- mock_sr |>
formatEstimateName(
estimateNameFormat = c(
"N (%)" = "<count> (<percentage>%)",
"N" = "<count>",
"Mean (SD)" = "<mean> (<sd>)"
),
keepNotFormatted = FALSE,
useFormatOrder = FALSE
)
mock_sr |> glimpse()
```
Additional input arguments are `keepNotFormatted` to specify whether not formatted rows should be returned or dropped, and `useFormatOrder` to define if rows should be sorted as in `estimateNameFormat` or if the original order should be kept. In the latter scenario, when more than one estimate is pulled together, the new estimate position will be the first of the estimates being merged.
## 3. formatHeader()
This function helps to create a nice header for a *flextable*, *gt* table and other table formatting packages.
To this aim, this function pivots the columns specified in `header` "widening" the table. The name of the new columns can be formatted with the arguments `header`, `delim`, `inlcudeHeaderName`, and `includeHeaderKey` to later convert obtain a nice header of the formatted table (*flextable* or *gt* table).
#### Header keys
There are 3 different types of headers, identified with the keys "header", "header_name", and "header_level".
- **header:** Header labels passed to `header` but which are not part of the input table (are not columns names or values).
- **header_name:** Header labels that come from column names in the input table.
- **header_level:** Header labels that come from values of selected columns in the input table.
For instance, we might want to pivot by "group_level" and have an upper header called "Names of the cohorts". To do that we would proceed as follows:
```{r}
mock_sr |>
formatHeader(
header = c("Names of the cohorts", "group_level"),
delim = "\n",
includeHeaderName = TRUE,
includeHeaderKey = TRUE
) |>
glimpse()
```
The labels indicating which type of header refers to in the new column names can be removed with `includeHeaderKey`. However, having these keys in our header will allow to style separately the different header types in the next step (`fxTable` and `gtTable`).
Continuing with our example, we want to pivot by strata (name and level), but, we do not want the column names to appear in the header:
```{r}
mock_sr <- mock_sr |>
mutate(across(c("strata_name", "strata_level"), ~ gsub("&&&", "and", .x))) |>
formatHeader(
header = c("Stratifications", "strata_name", "strata_level"),
delim = "\n",
includeHeaderName = FALSE,
includeHeaderKey = TRUE
)
mock_sr |> glimpse()
```
Notice, how we substitute the keyWord "&&&" to "and", to get a nice header.
## 4. gtTable() and fxTable()
Finally, we have the functions `gtTable` and `fxTable` which will transform our tibble into a *gt* or *flextable* object respectively. These functions provide several tools to personalise the formatted table.
### gtTable()
Let's start by manipulating the dataframe to have the columns that we want to display, and then use `gtTable` with default values:
```{r}
# first we select the columns we want:
mock_sr <- mock_sr |>
splitGroup() |>
select(!all_of(c("cdm_name", "result_type", "package_name",
"package_version", "estimate_type", "result_id",
"additional_name", "additional_level")))
mock_sr |> gtTable()
```
Now, we want to group results by "cohort_name". More specifically we want to have a row which the name of each cohort before the results of that cohort, and that *cohort1* comes before *cohort2*. Additionally, we want to merge those rows what contain the same information for all the columns. To get this table we will use `gtTable` as follows:
```{r}
mock_sr |>
gtTable(
groupNameCol = "cohort_name",
groupNameAsColumn = FALSE,
groupOrder = c("cohort1", "cohort2"),
colsToMergeRows = "all_columns"
)
```
We might also want to modify the default style of the table. For instance, we might want to highlight the cohort_name labels with a blue background, have the body text in red, and use a combination of orange and yellow for the header. We can do it with the `style` argument:
```{r}
mock_sr |>
gtTable(
style = list(
"header" = list(gt::cell_text(weight = "bold"),
gt::cell_fill(color = "orange")),
"header_level" = list(gt::cell_text(weight = "bold"),
gt::cell_fill(color = "yellow")),
"column_name" = gt::cell_text(weight = "bold"),
"group_label" = list(gt::cell_fill(color = "blue"),
gt::cell_text(color = "white", weight = "bold")),
"body" = gt::cell_text(color = "red")
),
groupNameCol = "cohort_name",
groupNameAsColumn = FALSE,
groupOrder = c("cohort1", "cohort2"),
colsToMergeRows = "all_columns"
)
```
### fxTable()
To obtain a similar result but with a *flextable* object, we can use `fxTable` with the same arguments as before, however, `style` must be adapted to use the *officer* package since it is the accepted by *flextable*.
```{r}
mock_sr |>
fxTable(
style = list(
"header" = list(
"cell" = officer::fp_cell(background.color = "orange"),
"text" = officer::fp_text(bold = TRUE)),
"header_level" = list(
"cell" = officer::fp_cell(background.color = "yellow"),
"text" = officer::fp_text(bold = TRUE)),
"column_name" = list("text" = officer::fp_text(bold = TRUE)),
"group_label" = list(
"cell" = officer::fp_cell(background.color = "blue"),
"text" = officer::fp_text(bold = TRUE, color = "white")),
"body" = list("text" = officer::fp_text(color = "red"))
),
groupNameCol = "cohort_name",
groupNameAsColumn = FALSE,
groupOrder = c("cohort1", "cohort2"),
colsToMergeRows = "all_columns"
)
```
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/vignettes/formatFunctions.Rmd
|
---
title: "split and unite functions"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{split and unite functions}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
warning = FALSE,
message = FALSE
)
```
**Split** and **unite** are complementary functions to manipulate dataframes in R. They work with summarised_results objects (see R package *omopgenerics*), but they can also support R dataframes from other classes.
## summarised_result
First, let's load relevant libraries and generate a mock summarised_result object to use in the following examples.
```{r setup}
library(visOmopResults)
library(dplyr)
mock_sr <- mockSummarisedResult()
mock_sr |> glimpse()
```
A summarised_result contains 3 types of name-level paired columns which are targeted by the set of unite and split functions. These are the **group** columns which typically can contain information about cohorts, **strata** columns which have data on stratification for each group, and finally the **additional** columns which include further information not covered by group and strata.
## Split functions
The idea of the split functions is to pivot the "name" (e.g. *group_name*) column to split each value of that column into a column in the dataframe, which values are taken by the "level" (e.g. *group_level*) column.
### splitGroup(), splitStrata(), and splitAdditional()
For instance, the `splitGroup` function will target the *group_name-group_level* columns as seen below.
```{r}
mock_sr |> splitGroup() |> glimpse()
```
Similar to `splitStrata`, the functions `splitGroup` will split *group_name* and *group_level* columns, while `splitAdditional` will split the additional name-level pair. Finally, the function `splitAll` will split group, strata, and additional at once. Note that after using `splitStrata` on our summarised_result object, we do no longer have a *strata_name-strata_level* pair, instead we have two new columns corresponding to the stratifications, *age_group* and *sex*.
```{r}
mock_sr |> splitStrata() |> glimpse()
mock_sr |> splitAdditional() |> glimpse()
mock_sr |> splitAll() |> glimpse()
```
#### !! Keyword: &&&
Looking at the results below, observe how the splitting was not only done by values in the "name" column, but also among values containing the key word "**&&&**". That is, "sex &&& age_group" was splitted into *sex* and *age_group* columns, instead of generating a column called "*sex &&& age_group*".
### splitNameLevel()
The function `splitNameLevel` provides a more tailored splitting of the dataframe. This function can take any dataframe with no restrictions to the naming of the name-level pair columns, since these can be specified in the `name` and `level` arguments.
For instance let's use it in the following table:
```{r}
data_to_split <- tibble(
denominator = "general_population",
outcome = "stroke",
input_arguments = c("wash_out &&& previous_observation"),
input_arguments_values = c("60 &&& 180")
)
data_to_split
```
```{r}
data_to_split |>
splitNameLevel(
name = "input_arguments",
level = "input_arguments_values"
)
```
The function `splitNameLevel`, in additionally to the argument `overall` previously seen, has the argument `keep` to set whether we want to keep the columns before the splitting.
## Unite functions
The unite functions are the complementary to the split ones. These are meant to generate name-level pair columns from targeted columns within a dataframe.
### uniteGroup(), uniteStrata(), and uniteAdditional()
To work with summarised_result objects, we have the `uniteGroup`, `uniteStrata`, and `uniteAdditional` functions which will generate the group, strata, and additional name-level columns respectively from a given set of columns. For instance, in the following example we want to create the *group_name* and *group_level* columns:
```{r}
to_unite_group <- tibble(
denominator_cohort_name = c("general_population", "older_than_60", "younger_than_60"),
outcome_cohort_name = c("stroke", "stroke", "stroke")
)
to_unite_group |>
uniteGroup(cols = c("denominator_cohort_name", "outcome_cohort_name"))
```
A part from the columns to unite argument (`cols`), there is the argument `ignore`, by default: `ignore = c(NA, "overall")`. This means that, levels within ignore will be ignored. For example if in this case we do not ignore them we will obtain the NA as output:
```{r}
to_unite_strata <- tibble(
age = c(NA, ">40", "<=40", NA, NA, NA, NA, NA, ">40", "<=40"),
sex = c(NA, NA, NA, "F", "M", NA, NA, NA, "F", "M"),
region = c(NA, NA, NA, NA, NA, "North", "South", "Center", NA, NA)
)
to_unite_strata |>
uniteStrata(cols = c("age", "sex", "region"),
ignore = character())
```
By default (`ignore = c(NA, "overall")`) we obtain an output where only names and levels of non-NA values are returned, and from those rows where all values are NA it uses "overall".
```{r}
to_unite_strata |>
uniteStrata(cols = c("age", "sex", "region"))
```
### uniteNameLevel()
Lastly, the function `uniteNameLevel`, idem to `splitNameLevel`, provides more flexibility on the name-level column naming, in addition of the `keep` argument (FALSE by default) to choose whether to keep the targeted columns. For instance, if we repeat the previous example with `keep` set to TRUE we would obtain the following output:
```{r}
to_unite_strata |>
uniteNameLevel(cols = c("age", "sex", "region"),
name = "name",
level = "level",
keep = TRUE)
```
|
/scratch/gouwar.j/cran-all/cranData/visOmopResults/vignettes/splitAndUnite.Rmd
|
#' Create a Survival Object from CDISC Data
#'
#' @description
#' `r lifecycle::badge('experimental')`
#'
#' The aim of `Surv_CNSR()` is to map the inconsistency in convention between
#' the [survival](https://cran.r-project.org/package=survival) package and
#' [CDISC ADaM ADTTE data model](https://www.cdisc.org/standards/foundational/adam/adam-basic-data-structure-bds-time-event-tte-analyses-v1-0).
#'
#' The function creates a survival object (e.g. `survival::Surv()`) that
#' uses CDISC ADaM ADTTE coding conventions and converts the arguments to the
#' status/event variable convention used in the
#' [survival](https://cran.r-project.org/package=survival) package.
#'
#' The `AVAL` and `CNSR` arguments are passed to
#' `survival::Surv(time = AVAL, event = 1 - CNSR, type = "right", origin = 0)`.
#'
#' @section Details:
#'
#' The `Surv_CNSR()` function creates a survival object utilizing the
#' expected data structure in the CDISC ADaM ADTTE data model,
#' mapping the CDISC ADaM ADTTE coding conventions with the expected
#' status/event variable convention used in the survival package---specifically,
#' the coding convention used for the status/event indicator.
#' The survival package expects the status/event indicator in the
#' following format: `0=alive`, `1=dead`. Other accepted choices are
#' `TRUE`/`FALSE` (`TRUE = death`) or `1`/`2` (`2=death`).
#' A final but risky option is to omit the indicator variable, in which case
#' all subjects are assumed to have an event.
#'
#' The CDISC ADaM ADTTE data model adopts a different coding convention for
#' the event/status indicator. Using this convention, the event/status variable
#' is named `'CNSR'` and uses the following coding: `censor = 1`, `status/event = 0`.
#'
#' @param AVAL The follow-up time. The follow-up time is assumed to originate from zero.
#' When no argument is passed, the default value is a column/vector named `AVAL`.
#' @param CNSR The censoring indicator where `1=censored` and `0=death/event`.
#' When no argument is passed, the default value is a column/vector named `CNSR`.
#'
#' @return Object of class 'Surv'
#' @seealso [`survival::Surv()`], [`estimate_KM()`]
#' @export
#'
#' @examples
#' # Use the `Surv_CNSR()` function with visR functions
#' adtte %>%
#' visR::estimate_KM(formula = visR::Surv_CNSR() ~ SEX)
#'
#' # Use the `Surv_CNSR()` function with functions from other packages as well
#' survival::survfit(visR::Surv_CNSR() ~ SEX, data = adtte)
#' survival::survreg(visR::Surv_CNSR() ~ SEX + AGE, data = adtte) %>%
#' broom::tidy()
Surv_CNSR <- function(AVAL, CNSR) {
# set default values if not passed by user -----------------------------------
if (missing(AVAL) && exists("AVAL", envir = rlang::caller_env())) {
AVAL <- get("AVAL", envir = rlang::caller_env())
} else if (missing(AVAL)) {
stop("Default 'AVAL' value not found. Specify argument in `Surv_CNSR(AVAL=)`.")
}
if (missing(CNSR) && exists("CNSR", envir = rlang::caller_env())) {
CNSR <- get("CNSR", envir = rlang::caller_env())
} else if (missing(CNSR)) {
stop("Default 'CNSR' value not found. Specify argument in `Surv_CNSR(CNSR=)`.")
}
# checking inputs ------------------------------------------------------------
if (!is.numeric(AVAL) || !is.numeric(CNSR)) {
stop("Expecting arguments 'AVAL' and 'CNSR' to be numeric.")
}
if (stats::na.omit(CNSR) %>% setdiff(c(0, 1)) %>%
{
!rlang::is_empty(.)
}) {
stop("Expecting 'CNSR' argument to be binary with values `0/1`.")
}
if (any(AVAL < 0)) {
warning("Values of 'AVAL' are less than zero, which is likely a data error.")
}
# pass args to `survival::Surv()` --------------------------------------------
survival::Surv(time = AVAL, event = 1 - CNSR, type = "right", origin = 0)
}
|
/scratch/gouwar.j/cran-all/cranData/visR/R/Surv_CNSR.R
|
#' @title Add confidence interval (CI) to visR object
#'
#' @description Method to add pointwise confidence intervals to a an object
#' created by visR through an S3 method. The method is set up to use
#' the pipe `%>%`. There are two options to display CI's, a "ribbon" or
#' as "step" lines.
#'
#' No default method is available at the moment.
#'
#' @param gg A ggplot created with visR
#' @param alpha aesthetic of ggplot2 \code{\link[ggplot2]{geom_ribbon}}. Default is 0.1.
#' @param style aesthetic of ggplot2 \code{\link[ggplot2]{geom_ribbon}}. Default is "ribbon". An alternative option is "step" that uses a line to display interval bounds.
#' @param linetype aesthetic of ggplot2 \code{\link[ggplot2]{geom_ribbon}}.
#' @param ... other arguments passed on to the method to modify \code{\link[ggplot2]{geom_ribbon}}
#'
#' @examples
#'
#' library(visR)
#'
#' # Estimate KM curves by treatment group
#' survfit_object <- survival::survfit(data = adtte, survival::Surv(AVAL, 1 - CNSR) ~ TRTP)
#'
#' ## plot without confidence intervals (CI)
#' p <- visR::visr(survfit_object)
#' p
#'
#' # add CI to plot with default settings
#' p %>% add_CI()
#'
#' # change transparency of CI ribbon
#' p %>% add_CI(alpha = 0.9, style = "ribbon")
#'
#' # plot CI as a step line instead of ribbon
#' p %>% add_CI(alpha = 0.1, style = "step")
#'
#' # change linetype of CI
#' p %>% add_CI(style = "step", linetype = 1)
#'
#' @return Pointwise confidence interval overlayed on a visR ggplot
#'
#' @rdname add_CI
#'
#' @export
add_CI <- function(gg, ...) {
UseMethod("add_CI", gg)
}
#' @rdname add_CI
#' @method add_CI ggsurvfit
#' @export
add_CI.ggsurvfit <- function(gg,
alpha = 0.1,
style = "ribbon",
linetype, ...) {
if (!base::all(c("est.lower", "est.upper") %in% colnames(gg$data))) {
stop("Confidence limits were not part of original estimation.")
}
if ((alpha > 1) | (alpha < 0)) {
warning("Invalid `alpha` argument, must be between 0 and 1. Setting it to 0.1.")
alpha <- 0.1
}
if (!base::any(c("ribbon", "step") %in% style)) {
warning("Invalid `style` argument. Setting `style` to `ribbon`.")
style <- "ribbon"
}
gg_gb <- ggplot2::ggplot_build(gg)
strata_colours <- unique(gg_gb$data[[1]]$colour)
if (style == "ribbon") {
if (!missing(linetype)) {
warning("Argument `linetype` not used for style ribbon.")
}
gg <- gg +
ggplot2::geom_ribbon(ggplot2::aes(
ymin = est.lower,
ymax = est.upper
),
stat = StatStepribbon,
na.rm = TRUE,
show.legend = FALSE
) +
ggplot2::scale_fill_manual(values = ggplot2::alpha(strata_colours, alpha))
}
if (style == "step") {
if (missing(linetype)) {
# Set a default linetype of solid (2) if the user didn't specify any
linetype <- 2
}
gg <- gg +
ggplot2::geom_ribbon(ggplot2::aes(
ymin = est.lower,
ymax = est.upper,
colour = strata
),
outline.type = "both",
linetype = linetype,
show.legend = FALSE,
na.rm = TRUE
) +
ggplot2::scale_fill_manual(values = ggplot2::alpha(strata_colours, 0))
}
return(gg)
}
#' @rdname add_CI
#' @method add_CI ggtidycuminc
#' @export
add_CI.ggtidycuminc <- add_CI.ggsurvfit
|
/scratch/gouwar.j/cran-all/cranData/visR/R/add_CI.R
|
#' @title Add censoring symbols to a visR object
#'
#' @description Add censoring symbols to a visR ggplot through an S3 method.
#' The S3 method is for adding censoring symbols to a visR ggplot.
#' The method is set up to use the pipe `%>%`.
#'
#' No default method is available at the moment.
#'
#' @param gg A ggplot created with visR
#' @param shape aesthetic of ggplot2 \code{\link[ggplot2]{geom_point}}. Default is 3.
#' @param size aesthetic of ggplot2 \code{\link[ggplot2]{geom_point}}. Default is 2.
#' @param ... other arguments passed on to the method to modify \code{\link[ggplot2]{geom_point}}
#'
#' @examples
#'
#' library(visR)
#'
#' # Estimate KM curves by treatment group
#' survfit_object <- survival::survfit(data = adtte, survival::Surv(AVAL, 1 - CNSR) ~ TRTP)
#'
#' ## plot without confidence intervals
#' p <- visR::visr(survfit_object)
#' p
#'
#' # add censoring to plot
#' p %>% visR::add_CNSR()
#'
#' # change censor symbol shape
#' p %>% visR::add_CNSR(shape = 1)
#'
#' # change size and shape
#' p %>% visR::add_CNSR(size = 4, shape = 2)
#'
#' @return Censoring symbols overlayed on a visR ggplot
#'
#' @rdname add_CNSR
#'
#' @export
add_CNSR <- function(gg, ...) {
UseMethod("add_CNSR", gg)
}
#' @rdname add_CNSR
#' @method add_CNSR ggsurvfit
#' @export
add_CNSR.ggsurvfit <- function(gg, shape = 3, size = 2, ...) {
if (!base::is.numeric(size)) {
if (base::is.list(size)) {
# ggplot technically allows a list of the same length as the elements to
# be plotted. However, we don't sanity check this and let ggplot deal with
# it: https://github.com/openpharma/visR/wiki/Don't-do-this
} else {
warning("Invalid `size` specified. Setting it to 2.")
size <- 2
}
}
if (!base::is.numeric(shape)) {
if (base::is.list(shape)) {
# ggplot technically allows a list of the same length as the elements to
# be plotted. However, we don't sanity check this and let ggplot deal with
# it: https://github.com/openpharma/visR/wiki/Don't-do-this
} else if (base::is.character(shape)) {
if (base::nchar(shape) > 1) {
warning("Invalid `shape` specified. If specifiyng a symbol, it must be a single character. Setting it to 3.")
shape <- 3
}
} else if ((base::is.na(shape)) || (base::is.null(shape))) {
warning("Invalid `shape` specified. Setting it to 3.")
shape <- 3
}
} else if ((shape < 0) | (shape > 25)) {
warning("Invalid `shape` specified. Values between [0-25] are supported. Setting it to 3.")
shape <- 3
}
gg <- gg +
ggplot2::geom_point(
data = base::subset(gg$data, n.censor >= 1),
ggplot2::aes(
x = time,
y = est,
color = strata
),
shape = shape,
size = size,
show.legend = FALSE
)
return(gg)
}
#' @export
#' @method add_CNSR ggtidycuminc
#' @rdname add_CNSR
add_CNSR.ggtidycuminc <- add_CNSR.ggsurvfit
|
/scratch/gouwar.j/cran-all/cranData/visR/R/add_CNSR.R
|
#' @title Add annotations to a visR object
#'
#' @description Wrapper around ggplot2::annotation_custom for simplified annotation to ggplot2 plots.
#' This function accepts a string, dataframe, data.table, tibble or customized
#' objects of class \code{gtable} and places them on the specified location on
#' the \code{ggplot}. The layout is fixed: bold column headers and plain body.
#' Only the font size and type can be chosen.
#' Both the initial plot as the individual annotation are stored as attribute `component`
#' in the final object.
#'
#' @seealso \code{\link[gridExtra]{tableGrob}} \code{\link[ggplot2]{annotation_custom}}
#'
#' @param gg Object of class \code{ggplot}.
#' @param label \code{String, dataframe, data.table, tibble} used to annotate the \code{ggplot}.
#' @param base_size \code{numeric}. Base font size in pt
#' @param base_family \code{character}. Base font family
#' @param xmin x coordinates giving horizontal location of raster in which to fit annotation.
#' @param xmax x coordinates giving horizontal location of raster in which to fit annotation.
#' @param ymin y coordinates giving vertical location of raster in which to fit annotation.
#' @param ymax y coordinates giving vertical location of raster in which to fit annotation.
#'
#' @examples
#' ## Estimate survival
#' surv_object <- visR::estimate_KM(data = adtte, strata = "TRTP")
#'
#' ## We want to annotate the survival KM plot with a simple string comment
#' visR::visr(surv_object) %>%
#' visR::add_annotation(
#' label = "My simple comment",
#' base_family = "sans",
#' base_size = 15,
#' xmin = 110,
#' xmax = 180,
#' ymin = 0.80
#' )
#'
#' ## Currently, care needs to be taken on the x-y values relative
#' ## to the plot data area. Here we are plotting outside of the data area.
#' visR::visr(surv_object) %>%
#' visR::add_annotation(
#' label = "My simple comment",
#' base_family = "sans",
#' base_size = 15,
#' xmin = 210,
#' xmax = 380,
#' ymin = 1.0
#' )
#'
#'
#' ## We may also want to annotate a KM plot with information
#' ## from additional tests or estimates. This example we annotate
#' ## with p-values contained in a tibble
#'
#' ## we calculate p-values for "Equality across strata"
#' lbl <- visR::get_pvalue(surv_object,
#' statlist = c("test", "pvalue"),
#' type = "All"
#' )
#'
#' ## display p-values
#' lbl
#'
#' ## Now annotate survival KM plot with the p-values
#' visR::visr(surv_object) %>%
#' visR::add_annotation(
#' label = lbl,
#' base_family = "sans",
#' base_size = 9,
#' xmin = 100,
#' xmax = 180,
#' ymin = 0.80
#' )
#'
#' @return Object of class \code{ggplot} with added annotation with an object of class \code{gtable}.
#'
#' @export
add_annotation <- function(gg = NULL,
label = NULL,
base_family = "sans",
base_size = 11,
xmin = -Inf,
xmax = Inf,
ymin = -Inf,
ymax = Inf) {
# User input validation ---------------------------------------------------
if (!base::inherits(gg, "ggplot")) stop("Error in add_annotation: gg is not of class `ggplot`")
if (is.null(label)) stop("Error in add_annotation: label does not exist")
if (!base_family %in% c("sans", "serif", "mono")) stop("Error in add_annotation: Specified font not supported")
if (!base::any(unlist(lapply(as.list(c(xmin, xmax, ymin, ymax, base_size)), is.numeric)))) stop("Error in add_annotation: One of the coordinates are not numeric.")
# ggtable -----------------------------------------------------------------
if (base::inherits(label, "gtable")) {
gganno <- gg +
ggplot2::annotation_custom(label, xmin = xmin, ymin = ymin, xmax = xmax, ymax = ymax)
### Add individual components
components <- append(list(gg), label) # Note: The append changes the structure of the gtable object
names(components) <- c("visR_plot", names(label))
gganno[["components"]] <- components
return(gganno)
} else {
### Prepare label: turn into dataframe and avoid factors + add manual bolding to avoid parsing issues with `` in colnames
df <- data.frame(lapply(label, as.character), stringsAsFactors = FALSE, check.names = FALSE) # as.character to protect leading zero in numeric
colnames(df) <- as.vector(paste(paste0("bold(\"", colnames(df), "\")")))
### Layout of gtable: access and modify options eg tt1$colhead
## First column to left, rest rightaligned
core_alignment_matrix <- matrix(rep(0, nrow(df) * dim(df)[2]), nrow = nrow(df), ncol = dim(df)[2])
if (dim(core_alignment_matrix)[2] > 1) {
core_alignment_matrix[, 2:dim(core_alignment_matrix)[2]] <- 1
}
core_alignment_head <- rep(1, dim(core_alignment_matrix)[2])
core_alignment_head[1] <- 0
tt1 <- gridExtra::ttheme_minimal(
base_size = base_size,
base_family = base_family,
core = list(
fg_params = list(
hjust = as.vector(core_alignment_matrix),
x = as.vector(core_alignment_matrix),
fontface = "plain"
)
),
colhead = list(
fg_params = list(
hjust = core_alignment_head,
x = core_alignment_head,
fontface = 2,
parse = TRUE
)
)
)
if (inherits(label, "character")) {
dfGrob <- gridExtra::tableGrob(df, rows = NULL, theme = tt1, cols = NULL)
} else {
dfGrob <- gridExtra::tableGrob(df, rows = NULL, theme = tt1)
}
gganno <- gg +
ggplot2::annotation_custom(dfGrob, xmin = xmin, ymin = ymin, xmax = xmax, ymax = ymax)
### Add individual components
components <- append(list(gg), dfGrob) # Note: The append changes the structure of the tableGrob object
names(components) <- c("visR_plot", names(dfGrob))
gganno[["components"]] <- components
return(gganno)
}
}
|
/scratch/gouwar.j/cran-all/cranData/visR/R/add_annotation.R
|
#' @title Highlight a specific strata
#'
#' @description S3 method for highlighting a specific strata by lowering the opacity of all other strata.
#'
#' @param gg A ggplot created with visR
#' @param strata String representing the name and value of the strata to be highlighted as shown in the legend.
#' @param bg_alpha A numerical value between 0 and 1 that is used to decrease the opacity off all strata not chosen to be highlighted in `strata`. The other strata's existing alpha values are multiplied by `bg_alpha` to decrease their opacity, highlighting the target strata. This works on both `colour` and `fill` properties, as for example present after applying `visR::add_CI()`.
#' @param ... other arguments passed on to the method
#'
#' @examples
#'
#' adtte %>%
#' visR::estimate_KM(strata = "SEX") %>%
#' visR::visr() %>%
#' visR::add_CI(alpha = 0.4) %>%
#' visR::add_highlight(strata = "M", bg_alpha = 0.2)
#'
#' strata <- c("Placebo", "Xanomeline Low Dose")
#'
#' adtte %>%
#' visR::estimate_KM(strata = "TRTP") %>%
#' visR::visr() %>%
#' visR::add_CI(alpha = 0.4) %>%
#' visR::add_highlight(strata = strata, bg_alpha = 0.2)
#'
#' @return The input `ggsurvfit` object with adjusted `alpha` values
#'
#' @rdname add_highlight
#'
#' @export
add_highlight <- function(gg, ...) {
UseMethod("add_highlight", gg)
}
#' @rdname add_highlight
#' @method add_highlight ggsurvfit
#' @export
add_highlight.ggsurvfit <- function(gg = NULL,
strata = NULL,
bg_alpha = 0.2,
...) {
# Ugly hack to suppress CRAN warning as described here:
# https://www.r-bloggers.com/2019/08/no-visible-binding-for-global-variable/#option-two
alpha <- colour <- fill <- group <- NULL
if (!inherits(gg, "ggplot")) {
stop("A 'ggplot' has to be specified for 'gg'.")
}
if (missing(strata) | length(strata) == 0) {
stop("Please specify one or more 'strata' to highlight.")
}
if (length(strata) == 1) {
if (inherits(strata, "list")) {
if (!inherits(strata, "character")) {
stop("A 'strata' must be either a single character string or a list of them.")
}
} else if (!inherits(strata, "character")) {
stop("A 'strata' must be either a single character string or a list of them.")
}
} else if (length(strata) > 1) {
if (is.list(strata)) {
strata <- unlist(strata)
}
base::sapply(strata, function(s) {
if (!inherits(s, "character")) {
stop("When 'strata' is a list, all elements must be character strings.")
}
})
}
if (!is.numeric(bg_alpha)) {
stop("The `bg_alpha` must be a `numeric`.")
}
if (bg_alpha > 1 | bg_alpha < 0) {
stop("The `bg_alpha` must be a numeric value between 0 and 1.")
}
# Extract names of strata objects
gg_gb <- ggplot2::ggplot_build(gg)
if ("get_guide_data" %in% getNamespaceExports("ggplot2")) {
get_guide_data <- get("get_guide_data", asNamespace("ggplot2"))
strata_labels <- get_guide_data(gg_gb, "colour")$.label
} else {
gg_gtable <- ggplot2::ggplot_gtable(gg_gb)
gg_guidebox_id <- base::which(base::sapply(
gg_gtable$grobs,
function(x) x$name
) == "guide-box")
gg_table_grob <- gg_gtable$grobs[[gg_guidebox_id]]$grobs[[1]]
# Get IDs of elements containing strata labels
strata_label_ids <- base::grep("label", gg_table_grob$layout$name)
extract_strata_name_by_id <- function(gg_table_grob, id) {
label <- gg_table_grob$grobs[[id]]$children[[1]]$children[[1]]$label
return(label)
}
strata_labels <- base::sapply(strata_label_ids,
extract_strata_name_by_id,
gg_table_grob = gg_table_grob
)
}
base::sapply(c(strata), function(s) {
if (!(s %in% strata_labels)) {
msg <- "The strata you specified has not been found in the provided plot.\n"
msg <- base::paste0(
msg,
" Available strata: ",
base::paste(strata_labels, collapse = ", "),
"\n"
)
msg <- base::paste0(msg, " Please adjust and rerun.")
stop(msg)
}
})
# Which group(s) in the ggplot data object corresponds to the bg strata?
bg_strata_ids <- unique(gg_gb$data[[1]]$group)[!(strata_labels %in% strata)]
# Replace the previous hex alpha values with the new one
for (i in 1:base::length(gg_gb$data)) {
if ("ymin" %in% base::colnames(gg_gb$data[[i]])) {
# Check whether colour contains an alpha value
if (base::nchar(gg_gb$data[[i]]$fill[[1]])) {
gg_gb$data[[i]] <- gg_gb$data[[i]] %>%
dplyr::rowwise() %>%
dplyr::mutate(alpha = .get_alpha_from_hex_colour(fill)) %>%
as.data.frame()
}
gg_gb$data[[i]] <- gg_gb$data[[i]] %>%
dplyr::rowwise() %>%
dplyr::mutate(alpha = base::ifelse(is.na(alpha), 1, alpha)) %>%
dplyr::mutate(alpha = base::ifelse(group %in% bg_strata_ids,
alpha * bg_alpha,
alpha
)) %>%
dplyr::mutate(fill = .replace_hex_alpha(fill, .convert_alpha(numeric_alpha = alpha))) %>%
as.data.frame()
strata_colours <- unique(gg_gb$data[[i]]$fill)
suppressMessages(gg <- gg + ggplot2::scale_fill_manual(values = strata_colours))
} else {
gg_gb$data[[i]] <- gg_gb$data[[i]] %>%
dplyr::rowwise() %>%
dplyr::mutate(alpha = base::ifelse(is.na(alpha), 1, alpha)) %>%
dplyr::mutate(alpha = base::ifelse(group %in% bg_strata_ids,
alpha * bg_alpha,
alpha
)) %>%
dplyr::mutate(colour = paste0(colour, .convert_alpha(numeric_alpha = alpha))) %>%
as.data.frame()
strata_colours <- unique(gg_gb$data[[i]]$colour)
suppressMessages(gg <- gg + ggplot2::scale_color_manual(values = strata_colours))
}
}
return(gg)
}
|
/scratch/gouwar.j/cran-all/cranData/visR/R/add_highlight.R
|
#' @title Add quantile indicators to visR plot
#'
#' @description Method to add quantile lines to a plot.
#'
#' @param gg A ggplot created with visR
#' @param quantiles vector of quantiles to be displayed on the probability scale, default: 0.5
#' @param linetype string indicating the linetype as described in the aesthetics of ggplot2 \code{\link[ggplot2]{geom_line}}, default: dashed (also supports "mixed" -> horizontal lines are solid, vertical ones are dashed)
#' @param linecolour string indicating the linetype as described in the aesthetics of ggplot2 \code{\link[ggplot2]{geom_line}}, default: grey, (also supports "strata" -> horizontal lines are grey50, vertical ones are the same colour as the respective strata)
#' @param alpha numeric value between 0 and 1 as described in the aesthetics of ggplot2 \code{\link[ggplot2]{geom_line}}, default: 1
#' @param ... other arguments passed on to the method to modify \code{\link[ggplot2]{geom_line}}
#'
#' @examples
#'
#' library(visR)
#'
#' adtte %>%
#' estimate_KM("SEX") %>%
#' visr() %>%
#' add_quantiles()
#'
#' adtte %>%
#' estimate_KM("SEX") %>%
#' visr() %>%
#' add_quantiles(quantiles = c(0.25, 0.50))
#'
#' adtte %>%
#' estimate_KM("SEX") %>%
#' visr() %>%
#' add_quantiles(
#' quantiles = c(0.25, 0.50),
#' linetype = "solid",
#' linecolour = "grey"
#' )
#'
#' adtte %>%
#' estimate_KM("SEX") %>%
#' visr() %>%
#' add_quantiles(
#' quantiles = c(0.25, 0.50),
#' linetype = "mixed",
#' linecolour = "strata"
#' )
#'
#' @return Lines indicating the quantiles overlayed on a visR ggplot
#'
#' @rdname add_quantiles
#'
#' @export
add_quantiles <- function(gg, ...) {
UseMethod("add_quantiles", gg)
}
#' @rdname add_quantiles
#' @method add_quantiles ggsurvfit
#' @export
add_quantiles.ggsurvfit <- function(gg,
quantiles = 0.5,
linetype = "dashed",
linecolour = "grey50",
alpha = 1,
...) {
# no visible binding for global variable fix
name <- n <- group <- NULL
if (!is.numeric(quantiles)) {
warning("Invalid argument for `quantiles`, must be numeric. Setting it to 0.5.")
quantiles <- 0.5
}
if (!is.character(linetype)) {
warning("Invalid argument for `linetype`, must be a character string. Setting it to default 'dashed'.")
linetype <- "dashed"
}
if (!is.character(linecolour)) {
warning("Invalid argument for `linecolour`, must be a character string. Setting it to default 'grey50'.")
linecolour <- "grey50"
}
if ((alpha > 1) | (alpha < 0)) {
warning("Invalid `alpha` argument, must be between 0 and 1. Setting it to 1.0.")
alpha <- 1.0
}
call <- gg$data$call[[1]]
survfit_object <- rlang::eval_tidy(call)
main <- trimws(sub(".*~", "", as.character(rlang::quo_squash(call))[[2]]), which = "both")
if (is.null(survfit_object$strata) && main == "1") {
survfit_object$strata <- as.vector(length(survfit_object$time))
attr(survfit_object$strata, "names") <- "Overall"
}
survfit_object_quantiles <- survfit_object %>%
get_quantile(probs = quantiles) %>%
dplyr::filter(quantity == "quantile")
cols_to_pivot <- colnames(survfit_object_quantiles) %>%
setdiff(c("strata", "quantity"))
quantiles_long <- survfit_object_quantiles %>%
tidyr::pivot_longer(cols = cols_to_pivot) %>%
dplyr::rename(quantile = name) %>%
dplyr::mutate(group = paste(strata, quantile, sep = "_")) %>%
dplyr::rename(n = value) %>%
dplyr::mutate(surv = 1 - (as.numeric(quantile)) / 100) %>%
dplyr::select(-quantity)
# Extract fun potentially applied to y-axis and use for quantiles
.fun <- attr(gg, "fun")
quantiles_long <- quantiles_long %>%
dplyr::mutate(surv = .fun(1 - (as.numeric(quantile) / 100)))
horizontal_helper <- quantiles_long %>%
dplyr::mutate(n = 0)
# Get lower y-axis limit to drop the lines to
ggb <- ggplot2::ggplot_build(gg)
yaxis_min <- min(ggb$layout$panel_scales_y[[1]]$limits)
vertical_helper <- quantiles_long %>%
dplyr::mutate(surv = yaxis_min)
if (linetype == "mixed") {
linetype_horizontal <- "solid"
linetype_vertical <- "dashed"
} else {
linetype_horizontal <- linetype
linetype_vertical <- linetype
}
if (linecolour == "strata") {
linecolour_horizontal <- "grey50"
linecolour_vertical <- "strata"
} else {
linecolour_horizontal <- linecolour
linecolour_vertical <- linecolour
}
# Draw non-overlapping horizontal lines
gg <- gg +
ggplot2::geom_line(
data = rbind(quantiles_long, horizontal_helper) %>%
dplyr::group_by(surv) %>%
dplyr::filter(n == 0 | n == max(n)),
ggplot2::aes(
x = n,
y = surv,
group = group
),
linetype = linetype_horizontal,
colour = linecolour_horizontal,
alpha = alpha
)
if (linecolour_vertical == "strata") {
gg <- gg +
ggplot2::geom_line(
data = rbind(quantiles_long, vertical_helper),
ggplot2::aes(
x = n,
y = surv,
group = group,
colour = strata
),
linetype = linetype_vertical,
alpha = alpha
)
} else {
gg <- gg +
ggplot2::geom_line(
data = rbind(quantiles_long, vertical_helper),
ggplot2::aes(
x = n,
y = surv,
group = group
),
linetype = linetype_vertical,
colour = linecolour_vertical,
alpha = alpha
)
}
return(gg)
}
|
/scratch/gouwar.j/cran-all/cranData/visR/R/add_quantiles.R
|
#' @title Add risk tables to visR plots through an S3 method
#'
#' @description S3 method for adding risk tables to visR plots. The function has following workflow:
#' \itemize{
#' \item{
#' The risktables are calculated using \code{\link[visR]{get_risktable}}
#' }
#' \item{
#' The risktables are placed underneath visR plots using \code{\link[cowplot]{plot_grid}}
#' }
#' \item{
#' Both the initial visR plot as the individual risktables are stored as attribute `component`
#' in the final object to allow post-modification of the individual plots if desired
#' }
#' }
#'
#' @param gg visR plot of class `ggsurvfit` or `ggtidycmprsk`
#' @inheritParams get_risktable
#' @param rowgutter A numeric relative value between 0 and 1 indicates the height used by the table versus the height
#' used by the plot, as described in `cowplot::plot_grid(rel_heights=)`. The default is 0.16.
#' @seealso \code{\link[cowplot]{plot_grid}}
#' @param ... other arguments passed on to the method add_risktable
#'
#' @rdname add_risktable
#'
#' @export
add_risktable <- function(gg, ...) {
UseMethod("add_risktable", gg)
}
#' @examples
#'
#' ## Display 2 risk tables, 1 per statlist
#' adtte %>%
#' visR::estimate_KM(strata = "TRTP") %>%
#' visR::visr() %>%
#' visR::add_risktable(
#' label = c("Subjects at Risk", "Censored"),
#' statlist = c("n.risk", "n.censor", "n.event"),
#' group = "statlist"
#' )
#'
#' ## Display overall risk table at selected times
#' adtte %>%
#' visR::estimate_KM(strata = "TRTP") %>%
#' visR::visr() %>%
#' visR::add_risktable(
#' label = c("Subjects at Risk", "Censored"),
#' statlist = c("n.risk", "n.censor"),
#' collapse = TRUE,
#' times = c(0, 20, 40, 60)
#' )
#'
#' ## Add risk set as specified times
#' adtte %>%
#' visR::estimate_KM(strata = "TRTP") %>%
#' visR::visr() %>%
#' visR::add_risktable(times = c(0, 20, 40, 100, 111, 200))
#'
#' @return Object of class \code{ggplot} with added risk table.
#'
#' @rdname add_risktable
#'
#' @export
add_risktable.ggsurvfit <- function(gg,
times = NULL,
statlist = "n.risk",
label = NULL,
group = "strata",
collapse = FALSE,
rowgutter = .16,
...) {
# User input validation ---------------------------------------------------
if (!(is.numeric(rowgutter) == TRUE) || (rowgutter < 0) || (rowgutter > 1)) {
stop("rowgutter should be a numeric value in range [0, 1]")
}
# Obtain the relevant table --------------------------------------------------
tidy_object <- gg$data
estimate_object <- .extract_estimate_object(gg)
ggbld <- ggplot2::ggplot_build(gg)
graphtimes <- as.numeric(ggbld$layout$panel_params[[1]]$x$get_labels())
if (is.null(times)) times <- graphtimes
final <-
get_risktable(estimate_object,
times = times,
statlist = statlist,
label = label,
group = group,
collapse = collapse
)
times <- as.numeric(unique(final$time))
statlist <- attributes(final)$statlist
title <- attributes(final)$title
attr(final, "time_ticks") <- NULL
attr(final, "statlist") <- NULL
attr(final, "title") <- NULL
# Plot requested tables below using list approach with map function -------
tbls <-
base::Map(function(statlist, title = NA) {
ggrisk <- ggplot2::ggplot(
final,
ggplot2::aes(
x = time,
y = stats::reorder(y_values, dplyr::desc(y_values)),
label = format(get(statlist), nsmall = 0) # = value columns
)
) +
ggplot2::geom_text(size = 3.0, hjust = 0.5, vjust = 0.5, angle = 0, show.legend = FALSE) +
ggplot2::theme_bw() +
ggplot2::scale_x_continuous(
breaks = graphtimes,
limits = c(min(graphtimes), max(graphtimes))
) +
ggplot2::theme(
axis.title.x = ggplot2::element_text(
size = 8,
vjust = 1,
hjust = 1
),
panel.grid.major = ggplot2::element_blank(),
panel.grid.minor = ggplot2::element_blank(),
panel.border = ggplot2::element_blank(),
axis.line = ggplot2::element_blank(),
axis.text.x = ggplot2::element_blank(),
axis.ticks = ggplot2::element_blank(),
axis.text.y = ggplot2::element_text(size = 8, colour = "black", face = "plain"),
plot.margin = ggplot2::unit(c(1, 0, 0, 0), "lines"),
plot.title = ggplot2::element_text(hjust = 0, vjust = 0),
legend.position = "none"
) +
ggplot2::xlab(NULL) +
ggplot2::ylab(NULL)
if (!is.na(title) && !is.null(title)) {
ggrisk <- ggrisk +
ggplot2::ggtitle(title) +
ggplot2::theme(plot.title = ggplot2::element_text(size = 10))
}
return(ggrisk)
},
statlist = as.list(statlist),
title = as.list(title)
)
# Align plot and table by adjusting width ---------------------------------
gglist <- list(gg) %>%
base::append(tbls)
ggA <- gglist %>%
align_plots()
# Create plot and add class -----------------------------------------------
## cowplot allows to align according to an axis (+left) and change the heigth
ggB <- cowplot::plot_grid(
plotlist = ggA,
align = "none",
nrow = length(ggA),
rel_heights = c(1 - (rowgutter * (length(ggA) - 1)), rep(rowgutter, length(ggA) - 1))
)
class(ggB) <- c(class(ggB), intersect(class(gg), c("ggsurvfit", "ggtidycmprsk")))
# Add individual components -----------------------------------------------
components <- append(list(gg), tbls)
names(components) <- c("visR_plot", title)
ggB[["components"]] <- components
return(ggB)
}
#' @rdname add_risktable
#' @export
add_risktable.ggtidycuminc <- add_risktable.ggsurvfit
|
/scratch/gouwar.j/cran-all/cranData/visR/R/add_risktable.R
|
#' @title Apply list of inclusion/exclusion criteria to a patient-level dataframe
#'
#' @description
#' `r lifecycle::badge("questioning")`
#' Apply list of inclusion/exclusion criteria to a patient-level dataframe
#'
#' @param data \code{data.frame}. Data set to be filtered
#' @param criteria_conditions \code{character} dplyr-filter compatible conditions
#' of the filtering criteria. These conditions will be applied to filter the input
#' data set and obtain final analysis data set
#'
#' @return Filtered data frame
#' @export
#'
#' @examples
#' adtte_filtered <- visR::apply_attrition(adtte,
#' criteria_conditions = c(
#' "TRTP=='Placebo'", "AGE>=75",
#' "RACE=='WHITE'", "SITEID==709"
#' )
#' )
#'
apply_attrition <- function(data, criteria_conditions) {
if (missing(data)) {
stop("Please provide input dataframe.")
}
if (missing(criteria_conditions)) {
stop("Please provide a character vector with conditions to filter input data.")
}
if (rlang::is_empty(criteria_conditions)) {
stop("Please provide a non-empty list of filtering critera as strings for the data.")
}
filters <- paste(criteria_conditions, collapse = ") & (") %>% paste0("(", ., ")")
adf <- data %>%
dplyr::filter(eval(parse(text = filters)))
return(adf)
}
|
/scratch/gouwar.j/cran-all/cranData/visR/R/apply_attrition.R
|
#' @title Applies a theme to a ggplot object.
#'
#' @description
#' `r lifecycle::badge("experimental")`
#' Takes in the styling options defined through `visR::define_theme` and applies them to a plot.
#'
#' @param gg object of class \code{ggplot}
#' @param visR_theme_dict nested list containing possible font options
#'
#' @return object of class \code{ggplot}
#'
#' @examples
#'
#' library(visR)
#'
#' theme <- visR::define_theme(
#' strata = list(
#' "SEX" = list(
#' "F" = "red",
#' "M" = "blue"
#' ),
#' "TRTA" = list(
#' "Placebo" = "cyan",
#' "Xanomeline High Dose" = "purple",
#' "Xanomeline Low Dose" = "brown"
#' )
#' ),
#' fontsizes = list(
#' "axis" = 12,
#' "ticks" = 10,
#' "legend_title" = 10,
#' "legend_text" = 8
#' ),
#' fontfamily = "Helvetica",
#' grid = FALSE,
#' bg = "transparent",
#' legend_position = "top"
#' )
#'
#'
#' gg <- adtte %>%
#' visR::estimate_KM(strata = "SEX") %>%
#' visR::visr() %>%
#' visR::apply_theme(theme)
#' gg
#'
#' @export
apply_theme <- function(gg, visR_theme_dict = NULL) {
# Manually define colour-blind friendly palette, taken from
# http://mkweb.bcgsc.ca/biovis2012/krzywinski-visualizing-biological-data.pdf
coldefault <- c(
grDevices::rgb(0, 0, 0, maxColorValue = 255), # 1
grDevices::rgb(73, 0, 146, maxColorValue = 255), # 6
grDevices::rgb(146, 0, 0, maxColorValue = 255), # 11
grDevices::rgb(0, 146, 146, maxColorValue = 255), # 3
grDevices::rgb(182, 109, 255, maxColorValue = 255), # 8
grDevices::rgb(219, 209, 0, maxColorValue = 255), # 13
grDevices::rgb(255, 182, 119, maxColorValue = 255), # 5
grDevices::rgb(182, 219, 255, maxColorValue = 255), # 10
grDevices::rgb(255, 255, 109, maxColorValue = 255), # 15
grDevices::rgb(0, 73, 73, maxColorValue = 255), # 2
grDevices::rgb(0, 109, 219, maxColorValue = 255), # 7
grDevices::rgb(146, 73, 0, maxColorValue = 255), # 12
grDevices::rgb(255, 109, 182, maxColorValue = 255), # 4
grDevices::rgb(109, 182, 255, maxColorValue = 255), # 9
grDevices::rgb(36, 255, 36, maxColorValue = 255) # 14
)
skipcolordef <- FALSE
skipcolor <- TRUE
font_family <- ggplot2::element_text(family = "Helvetica")
legend_title <- ggplot2::element_text(size = 12)
legend_text <- ggplot2::element_text(size = 10)
legend_position <- NULL
axis_text <- ggplot2::element_text(size = 10)
axis_title <- ggplot2::element_text(
size = 12,
margin = ggplot2::margin(
t = 6,
r = 6,
b = 6,
l = 6,
unit = "pt"
)
)
panel_grid_major <- ggplot2::element_blank()
panel_grid_minor <- ggplot2::element_blank()
panel_background <- ggplot2::element_rect(fill = "transparent")
plot_background <- ggplot2::element_rect(fill = "transparent")
if (!is.null(visR_theme_dict)) {
if (!inherits(visR_theme_dict, "visR_theme")) {
base::message("It is recommended to generate the theme object through `visR::define_theme`. Attempting to use the provided object anyway.")
}
if ("strata" %in% base::names(visR_theme_dict)) {
cols <- c()
skipcolordef <- TRUE
skipcolor <- FALSE
named_strata <- base::names(visR_theme_dict[["strata"]])
for (s in named_strata) {
values <- visR_theme_dict[["strata"]][[s]]
for (v in names(values)) {
name <- v
cols[[name]] <- values[[v]]
}
}
cols <- unlist(cols)
# find group used in plot and extract levels from the data => select these from cols
# if these levels were not defined, use default as present in plot
colneed <- as.character(unique(gg$data[[gg$labels$group]]))
# Take title to match strata in theme
lvl1 <- lapply(visR_theme_dict[["strata"]], unlist)
lvl2 <- lapply(lvl1, function(x) any(colneed %in% names(x)))
ttl <- names(which(lvl2 == TRUE))
# from the strata in the theme, which were used in the estimation
if (!any(colneed %in% names(cols))) {
skipcolor <- TRUE
}
if (length(colneed) > length(coldefault)) {
## too many strata, keep as is
# layer <- ggplot2::layer_data(gg)
# cols <- layer[unique(layer[["group"]]), "colour"]
# names(cols) <- colneed
skipcolordef <- FALSE
skipcolor <- TRUE
} else if (length(intersect(names(cols), colneed)) > 0) {
cols <- cols[intersect(names(cols), colneed)]
} else if (length(colneed) <= length(coldefault)) {
cols <- coldefault[1:length(colneed)]
names(cols) <- colneed
skipcolordef <- FALSE
}
}
# fonts and text -----------------------------------------------------------
if ("fontsizes" %in% base::names(visR_theme_dict)) {
if (is.numeric(visR_theme_dict[["fontsizes"]])) {
default_fontsize <- visR_theme_dict[["fontsizes"]]
axis_margin <- base::floor(default_fontsize / 2)
axis_title <- ggplot2::element_text(
size = default_fontsize,
margin = ggplot2::margin(
t = axis_margin,
r = axis_margin,
b = axis_margin,
l = axis_margin,
unit = "pt"
)
)
axis_text <- ggplot2::element_text(size = default_fontsize)
legend_title <- ggplot2::element_text(size = default_fontsize)
legend_text <- ggplot2::element_text(size = default_fontsize)
} else if (is.list(visR_theme_dict[["fontsizes"]])) {
if ("axis" %in% names(visR_theme_dict[["fontsizes"]])) {
axis_title_fontsize <- visR_theme_dict[["fontsizes"]][["axis"]]
axis_margin <- base::floor(axis_title_fontsize / 2)
axis_title <- ggplot2::element_text(
size = axis_title_fontsize,
margin = ggplot2::margin(
t = axis_margin,
r = axis_margin,
b = axis_margin,
l = axis_margin,
unit = "pt"
)
)
}
if ("ticks" %in% names(visR_theme_dict[["fontsizes"]])) {
axis_text <- ggplot2::element_text(size = visR_theme_dict[["fontsizes"]][["ticks"]])
}
if ("legend_title" %in% names(visR_theme_dict[["fontsizes"]])) {
legend_title <- ggplot2::element_text(size = visR_theme_dict[["fontsizes"]][["legend_title"]])
}
if ("legend_text" %in% names(visR_theme_dict[["fontsizes"]])) {
legend_text <- ggplot2::element_text(size = visR_theme_dict[["fontsizes"]][["legend_text"]])
}
}
}
if ("fontfamily" %in% base::names(visR_theme_dict)) {
font_family <- ggplot2::element_text(family = visR_theme_dict[["fontfamily"]])
}
# grid ---------------------------------------------------------------------
if ("grid" %in% base::names(visR_theme_dict)) {
if (is.logical(visR_theme_dict[["grid"]])) {
if (visR_theme_dict[["grid"]] == FALSE) {
panel_grid_major <- ggplot2::element_blank()
panel_grid_minor <- ggplot2::element_blank()
} else if (visR_theme_dict[["grid"]] == TRUE) {
panel_grid_major <- ggplot2::element_line()
panel_grid_minor <- ggplot2::element_line()
}
} else if (is.list(visR_theme_dict[["grid"]])) {
if ("major" %in% base::names(visR_theme_dict[["grid"]])) {
if (visR_theme_dict[["grid"]][["major"]] == FALSE) {
panel_grid_major <- ggplot2::element_blank()
} else if (visR_theme_dict[["grid"]][["major"]] == TRUE) {
panel_grid_major <- ggplot2::element_line()
} else {
base::warning("Invalid argument for `theme[[\"grid\"]][[\"major\"]]`. Please use `TRUE` or `FALSE`. Setting to default `FALSE`.")
}
}
if ("minor" %in% base::names(visR_theme_dict[["grid"]])) {
if (visR_theme_dict[["grid"]][["minor"]] == FALSE) {
panel_grid_minor <- ggplot2::element_blank()
} else if (visR_theme_dict[["grid"]][["minor"]] == TRUE) {
panel_grid_minor <- ggplot2::element_line()
} else {
base::warning("Invalid argument for `theme[[\"grid\"]][[\"minor\"]]`. Please use `TRUE` or `FALSE`. Setting to default `FALSE`.")
}
}
if (!("major" %in% base::names(visR_theme_dict[["grid"]])) &
!("minor" %in% base::names(visR_theme_dict[["grid"]]))) {
base::warning("Could find neither `theme[[\"grid\"]][[\"major\"]]` nor `theme[[\"grid\"]][[\"minor\"]]`. Setting to default `FALSE`.")
panel_grid_major <- ggplot2::element_blank()
panel_grid_minor <- ggplot2::element_blank()
}
}
} else {
panel_grid_major <- ggplot2::element_blank()
panel_grid_minor <- ggplot2::element_blank()
}
# background ---------------------------------------------------------------
if ("bg" %in% base::names(visR_theme_dict)) {
bg_colour <- visR_theme_dict[["bg"]]
panel_background <- ggplot2::element_rect(fill = bg_colour)
plot_background <- ggplot2::element_rect(fill = bg_colour)
}
# legend position ----------------------------------------------------------
if ("legend_position" %in% base::names(visR_theme_dict)) {
legend_position <- visR_theme_dict[["legend_position"]]
} else {
ggb <- ggplot2::ggplot_build(gg)
legend_position <- ggb$plot$theme$legend.position
}
}
if (is.null(legend_position)) {
ggb <- ggplot2::ggplot_build(gg)
legend_position <- ggb$plot$theme$legend.position
}
# Reset background
gg <- gg + ggplot2::theme_minimal()
if (!skipcolor) {
gg <- gg +
ggplot2::scale_colour_manual(
labels = names(cols),
values = cols,
aesthetics = c("colour", "fill"), na.value = "grey50"
) +
ggplot2::guides(color = ggplot2::guide_legend(ttl))
} else if (!skipcolordef) {
## apply color friendly palette
if (length(unique(ggplot2::layer_data(gg)[["group"]])) > length(coldefault)) {
warning(paste0(length(coldefault), " is the max. number of strata supported."))
} else {
gg <- gg +
ggplot2::scale_colour_manual(
values = coldefault,
aesthetics = c("colour", "fill"), na.value = "grey50"
)
}
}
gg <- gg +
ggplot2::theme(
text = font_family,
axis.title.x = axis_title,
axis.title.y = axis_title,
axis.text = axis_text,
legend.title = legend_title,
legend.text = legend_text,
panel.grid.major = panel_grid_major,
panel.grid.minor = panel_grid_minor,
panel.background = panel_background,
plot.background = plot_background,
legend.position = legend_position
)
return(gg)
}
# END OF CODE -------------------------------------------------------------
|
/scratch/gouwar.j/cran-all/cranData/visR/R/apply_theme.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.