Movatterモバイル変換


[0]ホーム

URL:


Version:3.0.4
Title:Descriptive Statistics, Transition Plots, and More
Description:Utilities for common medical-statistics graphics and tables, including automatic creation of publication-ready "Table 1" summaries; transition (Sankey) plots; flow-chart helpers that extend the grid package; Bézier lines and arrows; and a singular-value-decomposition- based variable-selection method.
License:GPL (≥ 3)
URL:https://gforge.se
BugReports:https://github.com/gforge/Gmisc/issues
Depends:R (≥ 4.1.0), Rcpp (≥ 0.11.4), htmlTable (≥ 2.0.0)
Imports:abind, checkmate, forestplot, Hmisc, glue, grid, grDevices,graphics, knitr, lattice, lubridate, magrittr, methods, rlang,rmarkdown, stringr, stats, XML, yaml, utils
Suggests:datasets, dplyr, jsonlite, testthat, tidyselect
Encoding:UTF-8
NeedsCompilation:yes
LinkingTo:Rcpp
VignetteBuilder:knitr
RoxygenNote:7.3.2
Packaged:2025-08-19 07:53:57 UTC; max
Author:Max Gordon [aut, cre]
Maintainer:Max Gordon <max@gforge.se>
Repository:CRAN
Date/Publication:2025-08-19 09:30:15 UTC

Collection of functions for plotting relations, generating tables, and more.

Description

This is a collection of functions that I've found useful in my research.The package is inspired by Frank Harrell'sHmisc package. The main focusis on tables, plots, andknitr-integration.

Awesome tables

ThegetDescriptionStatsBy is a straight forward function thataims at helping you to generate descriptive table stratified by differentvariables. In other words, the function returns everything you need for generatingaTable 1 ready for publication. This function is accompanied by thedescribeMean,describeMedian,describeProp,anddescribeFactors functions.

ThemergeDesc allows you to merge a set of outputsgetDescriptionStatsByinto ahtmlTable with the rgroup arguments automaticallygenerated, seevignette("descriptives", package = "Gmisc") for adetailed workflow description.

Some fancy plots

The transition plot function,transitionPlot, is fordescriptive purposes. It tries to illustrate the size of changebetween one state and the next, i.e. a transition. This isbasically a graph of based upontable(var1, var2).

TheSingular value decompositionis a common method for reducing the number of variables. Unfortunatelythis compression can reduce the interpretability of the model. ThegetSvdMostInfluentialfunction tries to remedy that by identifying the most influentialelements from theV-matrix.

Other stuff

TheinsertRowAndKeepAttr simply adds a row while rememberingall the attributes previously set by using thecopyAllNewAttributes.ThemergeLists tries to merge lists that do not have identicalelements.

Author(s)

Maintainer: Max Gordonmax@gforge.se

See Also

Useful links:


Deprecated function(s) inGmisc

Description

Theforestplot2 has moved toforestplot package and changed name toforestplot

Usage

forestplot2(...)

Arguments

...

Parameters to be passed to the new version of the function


A reference class for generating transition plots

Description

This class simplifies the creating of transition plots. It alsoallows for advanced multi-column transitions.

Details

Transition plots are a type ofSankey diagrams. These are a specific typeof flow diagram, in which the width of the arrows is shown proportionallyto the flow quantity. SeeWikipediafor details.

Fields

id

Optional id. The render uses named viewports that require a unique id if multiple transition plotsare combined. In order to avoid having overlapping graphs we need to generate a unique id for each viewportand thus this variable exists. If left empty it will create a counter that is stored in theoptions("Gmisc.transitionClassCounter") and each viewport will have the name preceded withtc_[0-9]+. Set thisif you intend to useseekViewport.

transitions

This is a >= 3 dimensional array with the transitions. Should not be directly accessed.

box_width

The box width

box_txt

The texts of each box

box_label

Box labels

box_label_pos

The label's positions, either "top"/"bottom"

box_label_cex

The size of the box labels

box_cex

The font-size multiplier for the text within the boxes

arrow_type

The type of arrow to use, defaults to "gradient", but can also be "simple".The corresponding functions arebezierArrowGradient, andbezierArrowSmpl.Note ThebezierGrob has been deprecatedas it is no longer faster than the bezier arrows and there is a difference in design.

arrow_clr

The arrow color

arrow_rez

The resolution of the arrow

vertical_space

The space between the boxes

fill_clr

The box fill color

clr_bar

Shows a color bar if there are proportions. Can be"none","top","bottom"

clr_bar_clrs

Extracts the colors for the color bar from thefill_clr if none is provided

clr_bar_cex

The size of the ticks in the color bar

clr_bar_subspace

If little or no difference exists at the low/high proportions ofthe spectrum then it can be of interest to focus the color change to the center leaving the tails constant

clr_bar_labels

The labels of the color bars. Defaults to the dim names for the proportions.

txt_clr

The text color within the boxes

txt_gpar

Similar to 'txt_clr' but for more advanced styling with fontfamily (see [grid::gpar()]). *Note* thatcol & cex are overridden.

title

The plot title if any

title_cex

The font-size multiplier for the title

skip_shadows

Skip the shadow effect on the boxes

mar

The margins for the plot.

min_lwd

The minimum line width that is still shown. The pixels will most likelynot have the same fine resolution as the data and you therefore may want to hidelines that are smaller than a certain amount.

max_lwd

The maximum line width to show

lwd_prop_type

The line can either be proportional to the"set" of transitions(group of two box columns), to"all" transitions, or to each"box". It defaultsto"all".

data

Internal storage variable. Should not be accessed directly.

Methods

addBoxStyle(fill, txt, gpar)

Adds colors or extends existing one so that they match the transition matrix.The fill corresponds to the fill_clr and txt corresponds to the txt_clr. Ifthe colors are missing and the transitions consist of only two columns the defaultcolors will be used. If the matrix is being extended and these values are missing thevalues from the previous last column will be used for the default columns.

addTransitions(mtrx, label, txt, fill_clr, txt_clr, txt_gpar)

Add a transition matrix. The input has to be a numerical matrix between 2 and 3 dimensions.If you don't provide the txt field the box' text field will be deduced from the transition matrix'dimnames. The fill_clr and txt_clr are passed on to theaddBoxStyle function.

arrowWidths(set_no, add_width)

Retrieves the details regarding arrow sizes for each arrow within the transitiongroup

boxPositions(col)

The box positions as a list with scalars for the positions:

  1. x The center x-position

  2. y The center y-position

  3. right The right edge

  4. left The left edge

  5. top The top edge

  6. bottom The bottom edge

  7. height The box height

  8. width The box width

  9. unit The unit used for the values (npc)

boxSizes(col)

Gets the size of the boxes. Thecol argument shouldbe either an integer or 'last'

getDim()

Gets the current dimensions of the transitions

getTransitionSet(no, reduce_dim = FALSE)

Gets a specific set of transitions. If thereduce_dim is setto TRUE it will only return a 2-dimensional matrix even if the originalhas a 3rd proportions dimension

getYProps(col)

Gets the proportions after removing thevertical_spacebetween the boxes

initialize(transitions, label, txt, fill_clr, txt_clr, txt_gpar, id, ...)

Set up a Transition object. Thetransitions should be a 2D or 3D matrixas defined in the$addTransitions section and not as later internally stored.

noCols()

Gets the number of columns, i.e. the number of transitions

noRows(no)

Gets the number of boxes in each row.If multiple rows the number of rows may differbetwen each transition matrix we therefore needto specify what transitions that we refer to.If no value is specified it returns all of them.

render(new_page = TRUE)

Call this to render the full graph. Thenew_page argumentis for creating a new plot, set this toFALSEif you want to combine this plot with another or if you haveadditional viewports that you intend to use.

trnstnSizes(set_no)

Gets the transitions per box as a 2D matrix. For the proportionsit also adds an attributeattr('props', prop_mtrx) thatis a 2D matrix with the corresponding proportions.

Examples

# Transitionsset.seed(1)n <- 10my_data <-  data.frame(    Var_a = sample(c(      "Test 1",      "Test 2",      "Test 3"    ),    size = n,    replace = TRUE,    prob = 3:1    ),    Var_b = sample(c(      "Test 1",      "Test 2",      "Test 3"    ),    size = n,    replace = TRUE,    prob = 1:3    )  )mtrx <- with(  my_data,  table(Var_a, Var_b))# Initialize the transition plottransitions <- getRefClass("Transition")$new(mtrx,                                             label = c("Before", "After"))# Render the plottransitions$render()

Align boxes

Description

Aligns a set ofboxGrob/boxPropGrob according to the first positional argument.

Usage

alignVertical(reference, ..., .position = c("center", "top", "bottom"))alignHorizontal(  reference,  ...,  .position = c("center", "left", "right"),  .sub_position = c("none", "left", "right"))

Arguments

reference

AboxGrob/boxPropGrob/coords object or aunit or anumerical value that can be converted into aunit ofnpc type.

...

A set of boxes.

.position

How to align the boxes, differs slightly for vertical and horizontal alignmentsee the accepted arguments

.sub_position

When the box is aboxPropGrob it not only has the general.positions butalsoleft andright which can be viewed as separate boxes that have simply been merged.

Value

list with the boxes that are to be aligned

See Also

Other flowchart components:boxGrob(),boxPropGrob(),connectGrob(),coords(),distance(),moveBox(),spread

Examples

library(grid)grid.newpage()box <- boxGrob("A cool\nreference\nbox",               x = .5, y = .8,               box_gp = gpar(fill = "#ADB5C7"))another_box <- boxGrob("A horizontal box", x = .1, y =  .5)yet_another_box <- boxGrob("Another horizontal box", x = .8, y = .3)alignedBoxes <- alignHorizontal(box,                                another_box,                                yet_another_box,                                .position = "right")boxfor (b in alignedBoxes) {  print(b)}vert_box <- boxGrob("Vert",                     x = .8, y = .3,                    box_gp = gpar(fill = "darkgreen"),                    txt_gp = gpar(col = "white"))another_vert_box <- boxGrob("Another vertical",                             x = .1, y =  .5,                            box_gp = gpar(fill = "darkgreen"),                            txt_gp = gpar(col = "white"))alignedBoxes <- alignVertical(box,                              vert_box,                              another_vert_box,                              .position = "bottom")for (b in alignedBoxes) {  print(b)}

Checks if unit or number 0-1

Description

Checks if unit or number 0-1

Assert that its a string or number

Assert valid color

Usage

assert_unit(var, allow_missing = TRUE)assert_label(var, allow_missing = TRUE)assert_just(var, allow_missing = TRUE)

Arguments

var

Variable 2 check

allow_missing

Allow missing variables

Value

void

void

void


A bezier arrow with gradient

Description

This is an experimental addition to the originalbezierArrowSmplwith the addition of a gradient in the center of the arrow that fades.

Usage

bezierArrowGradient(  x = c(0.2, 0.7, 0.3, 0.9),  y = c(0.2, 0.2, 0.9, 0.9),  width = 0.05,  clr = "#000000",  default.units = "npc",  align_2_axis = TRUE,  grdt_type = c("triangle", "rectangle"),  grdt_prop = 0.8,  grdt_decrease_prop = 0.5,  grdt_clr_prop = 0.7,  grdt_line_width,  grdt_clr = "#2F4F2F",  vp = NULL,  gp = gpar(),  rm_intersect = 3L,  ...)

Arguments

x

A numeric vector or unit object specifying x-locations ofspline control points.

y

A numeric vector or unit object specifying y-locations ofspline control points.

width

The width of the arrow, either a numeric single number or a unit.Note:The arrow does not rely onlwd but on actual width.

clr

The color of the arrow. This is the main color of the arrow and not the gradient color.

default.units

A string indicating the default units to useifx oryare only given as numeric vectors.

align_2_axis

Indicates if the arrow should be vertically/horizontallyaligned. This is useful for instance if the arrow attaches to a box.

grdt_type

The type of growth and gradient that is to be used,currently it only supports triangle (I'm considering adding bezier curvesbut currently I'm a little tired of coding)

grdt_prop

The proportion of the full length that should be a the gradient. The gradientconsists of three things:(1) the central band,(2) the slimming of the central band,(3) the color shift into the arrow color.Note that the the slimming and color proportions can be overlapping.

grdt_decrease_prop

The proportion of the gradient that should be decreasing,i.e. narrowing according to thegrdt_type argument.

grdt_clr_prop

The proportion of the gradient that should be converging to the arrow color.

grdt_line_width

The width of the border line. If not specified it defaults to 5 % ofthe original width, note the gradient's width is thus 90 %.

grdt_clr

The color of the gradient.

vp

A Grid viewport object (or NULL).

gp

An object of class"gpar", typically the outputfrom a call to the functiongpar. This is basicallya list of graphical parameter settings.

rm_intersect

Set to 0 if you want to skip intersection removal, 1 only to remove left or2 to only remove right. See details for why.

@section Remove intersections:

When the line is wide and the arrow has a narrow curve there may appear an empty triangle dueto polygon cancellation (two polygons within the same are cancel out). This behaviour may beugly and the function therefor tries to remove these.

Note: it is expensive to check if there are the lineas may intersect at one point,remove those unexpected, and then adjust the line to the new situation so that thetop and bottom lines match. It can also cause some unexpected behaviour why you may want toremove this feature if the arrow behaves erratically.

...

Passed on tobezierArrowSmpl

Value

A grob ofgList-type

Note

The triangle section of the arrow is not currently included in the gradient.

Examples

library(grid)grid.newpage()arrowGrob <- bezierArrowGradient(  x = c(.1, .3, .6, .9),  y = c(0.2, 0.2, 0.9, 0.9))grid.draw(arrowGrob)

A simple bezier arrow

Description

This is an alternative to the grid packagesbezierGrobwith the advantage that it allows you to draw an arrow with a specificunit width. Note, it has only a end-arrow at this point.

Usage

bezierArrowSmpl(  x = c(0.2, 0.7, 0.3, 0.9),  y = c(0.2, 0.2, 0.9, 0.9),  width = 0.05,  clr = "#000000",  default.units = "npc",  arrow = list(),  rez = 200,  align_2_axis = TRUE,  name = NULL,  rm_intersect = 3L,  gp = gpar(),  vp = NULL)

Arguments

x

A numeric vector or unit object specifying x-locations ofspline control points.

y

A numeric vector or unit object specifying y-locations ofspline control points.

width

The width of the arrow, either a numeric single number or a unit.Note:The arrow does not rely onlwd but on actual width.

clr

The color of the arrow.

default.units

A string indicating the default units to useifx oryare only given as numeric vectors.

arrow

This is a list with all thebase (width) and the desiredlength for the arrow.Note: This differs from the originalbezierGrob function.

rez

The resolution of the arrow. This specifies how many points to retrieve from thegnrlBezierPoints function. Defaults to 200.

align_2_axis

Indicates if the arrow should be vertically/horizontallyaligned. This is useful for instance if the arrow attaches to a box.

name

A character identifier.

rm_intersect

Set to 0 if you want to skip intersection removal, 1 only to remove left or2 to only remove right. See details for why.

@section Remove intersections:

When the line is wide and the arrow has a narrow curve there may appear an empty triangle dueto polygon cancellation (two polygons within the same are cancel out). This behaviour may beugly and the function therefor tries to remove these.

Note: it is expensive to check if there are the lineas may intersect at one point,remove those unexpected, and then adjust the line to the new situation so that thetop and bottom lines match. It can also cause some unexpected behaviour why you may want toremove this feature if the arrow behaves erratically.

gp

An object of class"gpar", typically the outputfrom a call to the functiongpar. This is basicallya list of graphical parameter settings.

vp

A Grid viewport object (or NULL).

Value

grid::grob A grob of the class polygonGrob with attributes thatcorrespond to the bezier points.

Examples

library(grid)grid.newpage()arrowGrob <- bezierArrowSmpl(  x = c(.1, .3, .6, .9),  y = c(0.2, 0.2, 0.9, 0.9))grid.draw(arrowGrob)

Create a box with text

Description

Creates agrob box with text inside it.

Usage

boxGrob(  label,  y = unit(0.5, "npc"),  x = unit(0.5, "npc"),  width,  height,  just = "center",  bjust = "center",  txt_gp = getOption("boxGrobTxt", default = gpar(color = "black", cex = 1)),  box_gp = getOption("boxGrob", default = gpar(fill = "white")),  box_fn = roundrectGrob,  name = NULL)## S3 method for class 'box'print(x, ...)## S3 method for class 'box'plot(x, ...)## S3 method for class 'box'widthDetails(x)## S3 method for class 'box'heightDetails(x)

Arguments

label

The label to print - should be a number, text or expression.

y

The y position to put the box at. Can be either innpc (i.e. 0-1) or aunit.

x

The x position to put the box at. Can be either innpc (i.e. 0-1) or aunit.

width

The box automatically adapts the size but you can force by specifying the width

height

The box automatically adapts the size but you can force by specifying the height

just

The justification for the text: left, center or right.

bjust

The justification for the box: left, center, right, top or bottom.See thejust option for theviewport

txt_gp

Thegpar style to apply to the text. SetboxGrobTxt optionif you want to customize all the boxes at once.

box_gp

Thegpar style to apply to the box function of 'box_fn' below.

box_fn

Function to create box for the text. Parameters of 'x=0.5', 'y=0.5' and 'box_gp' willbe passed to this function and return agrob object.

name

a character identifier for thegrob. Used to find thegrob on the displaylist and/or as a child of another grob.

...

Passed togrid.draw

Value

A grob

Theplot/print

To output thegrob objects to the plot either callploton the object orprint it. Note that R automatically prints any object that is outputtedto the console. The function calls in turn thegrid.draw function on the object.

S3 from thegrid package

Width and height functions address thecoords attribute for the corresponding information.ThewidthDetails andheightDetailsthat provide information on an object.

See Also

Other flowchart components:align,boxPropGrob(),connectGrob(),coords(),distance(),moveBox(),spread

Examples

library(grid)grid.newpage()boxGrob("My box")

Create a box with a color split

Description

Creates a grob box with text inside it and a color split in thehorizontal axes that allow indicating different proportions. Thebox can also have a title that spanse the two color areas andthat has its own background.

Usage

boxPropGrob(  label,  label_left,  label_right,  prop,  y = unit(0.5, "npc"),  x = unit(0.5, "npc"),  width,  height,  just = "center",  bjust = "center",  txt_gp = getOption("boxPropGrobTxt", default = gpar(color = "black")),  txt_left_gp = getOption("boxPropGrobLeftTxt", default = gpar(col = "black")),  txt_right_gp = getOption("boxPropGrobRightTxt", default = gpar(col = "black")),  box_left_gp = getOption("boxPropGrobLeft", default = gpar(fill = "#E6E8EF")),  box_right_gp = getOption("boxPropGrobRight", default = gpar(fill = "#FFFDF6")),  box_highlight_gp = getOption("boxPropGrobHighlight", default = gpar(fill = "#ffffff55",    col = NA)),  name = NULL)

Arguments

label

The label to print - should be a number, text or expression.

label_left

The label for the left area

label_right

The label for the right area

prop

The proportion to split along

y

The y position to put the box at. Can be either innpc (i.e. 0-1) or aunit.

x

The x position to put the box at. Can be either innpc (i.e. 0-1) or aunit.

width

The box automatically adapts the size but you can force by specifying the width

height

The box automatically adapts the size but you can force by specifying the height

just

The justification for the text: left, center or right.

bjust

The justification for the box: left, center, right, top or bottom.See thejust option for theviewport

txt_gp

Thegpar style to apply to the text. SetboxPropGrobTxt optionif you want to customize all the boxes at once.

txt_left_gp

Thegpar style to apply to the left text. SetboxPropGrobLeftTxt option if you want to customize all the boxes at once.

txt_right_gp

Thegpar style to apply to the right text. SetboxPropGrobRightTxt option if you want to customize all the boxes at once.

box_left_gp

Thegpar style to apply to the left box. SetboxPropGrobLeft option if you want to customize all the boxes at once.

box_right_gp

Thegpar style to apply to the right box. SetboxPropGrobRight option if you want to customize all the boxes at once.

box_highlight_gp

Thegpar style to apply to the backgroundof the main label. SetboxPropGrobHighlight option if you want to customizeall the boxes at once.

name

a character identifier for thegrob. Used to find thegrob on the displaylist and/or as a child of another grob.

Value

A box grob

See Also

Other flowchart components:align,boxGrob(),connectGrob(),coords(),distance(),moveBox(),spread

Examples

library(grid)grid.newpage()boxPropGrob("Main label", "Left text", "Right text", prop = .3)

Gets offsetted lines

Description

The function calculates new points according to the offsetthat lie to the left/right of the provided line.

Usage

calculateLinesAndArrow(  x,  y,  offset,  end_x = -1,  end_y = -1,  arrow_offset = -1,  rm_intersect = 3L)

Arguments

x

A numeric vector containing all the x-elements

y

A numeric vector containing all the y-elements

offset

The offset to add to the line, can be a vector if youwant to use different offsets.

end_x

The x end of the line where the arrow occurrs (if < 0 arrow is skipped)

end_y

The y end of the line where the arrow occurrs (if < 0 arrow is skipped)

arrow_offset

The offset to add to the arrow section if any (if <= 0 arrow is skipped)

rm_intersect

Set to 0 if you want to skip intersection removal, 1 only to remove left or2 to only remove right. See details for why.

@section Remove intersections:

When the line is wide and the arrow has a narrow curve there may appear an empty triangle dueto polygon cancellation (two polygons within the same are cancel out). This behaviour may beugly and the function therefor tries to remove these.

Note: it is expensive to check if there are the lineas may intersect at one point,remove those unexpected, and then adjust the line to the new situation so that thetop and bottom lines match. It can also cause some unexpected behaviour why you may want toremove this feature if the arrow behaves erratically.

Value

list(list(x = ..., y = ...)) Returns a list with the right/leftlines that in turn lists withx andy elements


Connect boxes with an arrow

Description

The function creates a grob that links two boxes together. It looks forwhich side it should attach the arrow, e.g. if the start is on top ofthe bottom it should attach to the bottom edge of ther start box and thento the top at the end.

Usage

connectGrob(  start,  end,  type = c("vertical", "horizontal", "L", "-", "Z", "N"),  subelmnt = c("right", "left"),  lty_gp = getOption("connectGrob", default = gpar(fill = "black")),  arrow_obj = getOption("connectGrobArrow", default = arrow(ends = "last", type =    "closed")))## S3 method for class 'connect_boxes'print(x, ...)## S3 method for class 'connect_boxes'plot(x, ...)

Arguments

start

The start box

end

The end box

type

How the boxes are stacked. TheL alternative generates astraight line up/down and then turns to righT/left for connecting with the end.The- generates a straight horizontal arrow. TheZ creates ahorizontal line that looks like aZ with 90 degree turns. The optionN allows for vertical lines.

subelmnt

If we have a split box we can specify the right/left x as theconnector point.

lty_gp

Thegpar for the line. SetconnectGrob option if you want to customize all the arrows at once.

arrow_obj

The arrow spec according toarrow. SetconnectGrobArrow option if you want to customize all the arrows at once.

x

The grob to print/plot

...

Passed togrid.draw

Details

The exact positions of the line is stored at theattr(..., "line").If you want to draw your own custom line all you need to do is check whichattr(my_line, "line")$x andattr(my_line, "line")$y you wantto attach to and then create your own customlinesGrob.

Value

grob with an arrow

See Also

Other flowchart components:align,boxGrob(),boxPropGrob(),coords(),distance(),moveBox(),spread

Examples

library(grid)grid.newpage()# Initiate the boxes that we want to connectstart <- boxGrob("Top", x = .5, y = .8)end <- boxGrob("Bottom", x = .5, y = .2)side <- boxPropGrob("Side", "Left", "Right", prop = .3, x = .2, y = .8)sub_side_left <- boxGrob("Left", x = attr(side, "coords")$left_x, y = .5)sub_side_right <- boxGrob("Right", x = attr(side, "coords")$right_x, y = .5)exclude <- boxGrob("Exclude:\n - Too sick\n - Prev. surgery", x = .8, y = .5, just = "left")# Connect the boxes and print/plot themconnectGrob(start, end, "vertical")connectGrob(start, side, "horizontal")connectGrob(side, sub_side_left, "v", "l")connectGrob(side, sub_side_right, "v", "r")connectGrob(start, exclude, "L")# Print the grobsstartendsideexcludesub_side_leftsub_side_right

A function for converting a show_missing variable.

Description

The variable is supposed to be directly compatible withtable(..., useNA = show_missing). It throws an errorif not compatible. It is mostly useful for custom describe functions.

Usage

convertShowMissing(show_missing)

Arguments

show_missing

Boolean or "no", "ifany", "always"

Details

Deprecated: This function will be deprecatedas all functions now use the useNA style in order to complywith standard R naming.

Value

string


Get the box coordinates

Description

Retrieves the boxes"coords" attribute.

Usage

coords(box)

Arguments

box

TheboxGrob orboxPropGrob

Value

A list with the coordinates

See Also

Other flowchart components:align,boxGrob(),boxPropGrob(),connectGrob(),distance(),moveBox(),spread

Examples

box <- boxGrob("A test box")coords(box)

A simple thing to keep the attributes

Description

Skips the attributes that the to object already hasto avoid overwriting dim and other important attributes

Usage

copyAllNewAttributes(from, to, attr2skip = c(), attr2force = c())

Arguments

from

The from object

to

The to object

attr2skip

An optional lists of attributesthat you may want to avoid having copied

attr2force

An optional lists of attributesthat you may want to force copy even if they alreadyexist in the new object

Value

object Theto argument object

Examples

a <- "test"attr(a, 'wow') <- 1000b <- ab <- copyAllNewAttributes(a, b)print(attr(b, 'wow'))

Get statistics for missing data

Description

This function calculates the amount of missing per row fordescribeMean,describeMedian and custom description functions.It will return invisibly when no missing values are present.

Usage

descGetMissing(  x,  html = TRUE,  number_first = TRUE,  percentage_sign = TRUE,  language = "en",  useNA.digits = 1,  ...)

Arguments

x

The variable that you want the statistics for

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

number_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().This is only used together with the useNA variable.

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable. Note, this isonly used when combined with the missing information.

language

The ISO-639-1 two-letter code for the language ofinterest. Currently only english is distinguished from the ISOformat using a ',' as the separator in thetxtIntfunction.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

...

Passed on todescribeFactors

Value

vector A vector with the missing estimate


Describes factor variables

Description

A function that returns a description of proportions in afactor that contains the number of times a level occurs and the percentage

Usage

describeFactors(  x,  html = TRUE,  digits = 1,  digits.nonzero = NA,  number_first = TRUE,  useNA = c("ifany", "no", "always"),  useNA.digits = digits,  horizontal_proportions,  percentage_sign = TRUE,  language = "en",  ...)

Arguments

x

The variable that you want the statistics for

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

digits

The number of decimals used

digits.nonzero

The number of decimals used for values that are close to zero

number_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().This is only used together with the useNA variable.

useNA

This indicates if missing should be added as a separaterow below all other. Seetable foruseNA-options.Note: defaults to ifany and not "no" astable does.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

horizontal_proportions

Is only active if useNA since this isthe only case of a proportion among continuous variables. This is default NULL and indicatesthat the proportions are to be interpreted in a vertical manner.If we want the data to be horizontal, i.e. the total should be shownand then how these differ in the different groups then supply thefunction with the total number in each group, i.e. if done in a bymanner as ingetDescriptionStatsBy it needs to providethe number before the by() command.

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable. Note, this isonly used when combined with the missing information.

language

The ISO-639-1 two-letter code for the language ofinterest. Currently only english is distinguished from the ISOformat using a ',' as the separator in thetxtIntfunction.

...

Passed on totxtInt

Value

A string formatted for printing either latex by HTML

See Also

getDescriptionStatsBy

Other descriptive functions:describeMean(),describeMedian(),describeProp(),getDescriptionStatsBy(),getPvalWilcox()

Examples

set.seed(1)describeFactors(sample(50, x = c("A", "B", "C"), replace = TRUE))n <- 500my_var <- factor(sample(size = n, x = c("A", "B", "C", NA), replace = TRUE))my_exp <- rbinom(n = n, size = 1, prob = 0.2)total <- table(my_var, useNA = "ifany")by(my_var,  INDICES = my_exp,  FUN = describeFactors,  useNA = "ifany",  horizontal_proportions = total)

Describe the mean

Description

A function that returns a description of a continuous variable usingthe mean together with the standard deviation. The standard deviationis used as it is "industry standard" to use mean with standard deviationand not because it's the only option.

Usage

describeMean(  x,  html = TRUE,  digits = 1,  digits.nonzero = NA,  number_first = TRUE,  useNA = c("ifany", "no", "always"),  useNA.digits = digits,  percentage_sign = TRUE,  plusmin_str,  language = "en",  ...)

Arguments

x

The variable that you want the statistics for

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

digits

The number of decimals used

digits.nonzero

The number of decimals used for values that are close to zero

number_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().This is only used together with the useNA variable.

useNA

This indicates if missing should be added as a separaterow below all other. Seetable foruseNA-options.Note: defaults to ifany and not "no" astable does.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable. Note, this isonly used when combined with the missing information.

plusmin_str

Provide if you want anything other than the plus minus signsuited for the given output format.

language

The ISO-639-1 two-letter code for the language ofinterest. Currently only english is distinguished from the ISOformat using a ',' as the separator in thetxtIntfunction.

...

Passed on todescribeFactors

Value

string Returns a string formatted for either LaTeX or HTML

See Also

getDescriptionStatsBy

Other descriptive functions:describeFactors(),describeMedian(),describeProp(),getDescriptionStatsBy(),getPvalWilcox()

Examples

describeMean(1:10)describeMean(c(1:10, NA), useNA = "always")describeMean(c(1:10, NA), useNA = "no")

A function that returns a description median that containsthe interquartile range or the full range

Description

A function that returns a description median that containsthe interquartile range or the full range

Usage

describeMedian(  x,  iqr = TRUE,  html = TRUE,  digits = 1,  digits.nonzero = NA,  number_first = TRUE,  useNA = c("ifany", "no", "always"),  useNA.digits = digits,  percentage_sign = TRUE,  language = "en",  ...)

Arguments

x

The variable that you want the statistics for

iqr

If interquartile range should be used

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

digits

The number of decimals used

digits.nonzero

The number of decimals used for values that are close to zero

number_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().This is only used together with the useNA variable.

useNA

This indicates if missing should be added as a separaterow below all other. Seetable foruseNA-options.Note: defaults to ifany and not "no" astable does.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable. Note, this isonly used when combined with the missing information.

language

The ISO-639-1 two-letter code for the language ofinterest. Currently only english is distinguished from the ISOformat using a ',' as the separator in thetxtIntfunction.

...

Passed on todescribeFactors

Value

string A string formatted for either LaTeX or HTML

See Also

getDescriptionStatsBy

Other descriptive functions:describeFactors(),describeMean(),describeProp(),getDescriptionStatsBy(),getPvalWilcox()

Examples

describeMedian(1:10)describeMedian(c(1:10, NA), useNA = "ifany")

A function that returns a description proportion that containsthe number and the percentage

Description

A function that returns a description proportion that containsthe number and the percentage

Usage

describeProp(  x,  html = TRUE,  digits = 1,  digits.nonzero = NA,  number_first = TRUE,  useNA = c("ifany", "no", "always"),  useNA.digits = digits,  default_ref = NULL,  percentage_sign = TRUE,  language = "en",  ...)

Arguments

x

The variable that you want the statistics for

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

digits

The number of decimals used

digits.nonzero

The number of decimals used for values that are close to zero

number_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().This is only used together with the useNA variable.

useNA

This indicates if missing should be added as a separaterow below all other. Seetable foruseNA-options.Note: defaults to ifany and not "no" astable does.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

default_ref

The default reference, either first,the level name or a number within the levels. If left outit defaults to the first value.

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable. Note, this isonly used when combined with the missing information.

language

The ISO-639-1 two-letter code for the language ofinterest. Currently only english is distinguished from the ISOformat using a ',' as the separator in thetxtIntfunction.

...

Passed on todescribeFactors

Value

string A string formatted for either LaTeX or HTML

See Also

Other descriptive functions:describeFactors(),describeMean(),describeMedian(),getDescriptionStatsBy(),getPvalWilcox()

Examples

describeProp(factor(sample(50, x = c("A", "B", NA), replace = TRUE)))

Get the distance between grid objects

Description

Retrieves the distance between two boxes as absolute"mm" units. The function alsoacceptscoords objects as well as aunit or a numeric input.

Usage

distance(  box1,  box2,  type = c("vertical", "horizontal", "euclidean"),  half = FALSE,  center = FALSE)## S3 method for class 'Gmisc_unit'print(x, ...)

Arguments

box1

The firstboxGrob. Can also be acoordsobject, aunit or a numeric. The latter is evaluated toaunit withunits="npc".

box2

The second object to calculate the distance to. Same type as forbox1.

type

Whether we should retrieve the vertical, horizontal or euclidean distance

half

If set to true it returns half the distance. This is convenientwhen positioning boxes between each other.

center

Calculate the distance from the center of each object

x

A unit with from thedistance function

...

Passed on to print

Value

Aunit in"mm" with an absolute value. The attributepositive indicates the direction of the value, i.e. if it isTRUE thedistance was calculated from the first to the second, otherwise it isFALSE.Foreuclidean distance thepositive attribute isNA. There is also thefrom andto attributes that has the coordinates that were used for thecalculations, foreuclidean distance this isNA.

See Also

Other flowchart components:align,boxGrob(),boxPropGrob(),connectGrob(),coords(),moveBox(),spread

Examples

box1 <- boxGrob("A test box", y = .8)box2 <- boxGrob("Another test box", y = .2)distance(box1, box2, "v")

Formatter wrapper forhtml_document, facilitates easier porting to docx

Description

This function adds the option of having adaptations needed for seemless integration withMS Word for importing html-documents in the .docx-format. The advantage of html documents isthe ability to create advanced formatting frequently needed in medical publicationsand that is available in thehtmlTable function. You can viewthe seriesfor more details regarding how to achievefast-track-publishing (ftp) together with knitr.

Usage

docx_document(  ...,  self_contained = FALSE,  mathjax = NULL,  theme = NULL,  highlight = NULL,  css = "rmarkdown/docx.css",  h1_style = "margin: 24pt 0pt 0pt 0pt;",  other_h_style = "margin: 10pt 0pt 0pt 0pt;",  remove_scripts = TRUE,  force_captions = FALSE,  css_max_width)

Arguments

...

Passed ontohtml_document.

self_contained

Overrides the defaultTRUE forhtml_document toFALSE asLibreOffice hangs on long lines such as the base64images included in the self-contained version.

mathjax

The advanced mathjax does not work with withWord/LibreOffice.

theme

No theme should be used for the output as thecustom CSS should take care of everything.

highlight

By default turn off highlighting as scriptsare difficult to import. This does though work somewhat OK whencopy-pasting from the web-browser.

css

The CSS if other that the default within the package

h1_style

You can choose any css style formatting here that youwant to be applied to all h1 elements. Note: this is only appliedif LibreOffice_adapt isTRUE.

other_h_style

This is the formatting applied to any otherh elements not included to the first. Note: this is only appliedif LibreOffice_adapt isTRUE.

remove_scripts

TRUE if <script></script> tags areto be removed. These are usually not compatible with Word-processorsand should therefore in most cases be stripped from the document.

force_captions

Since out.width and out.height remove the option ofhaving captions this allows a workaround through some processingvia the XML-package

css_max_width

The max width of the body element. Defaults to "40em"if not specified. Any CSS-compliant width format works.

Details

If you want to get equations into Word the currently best way is touse theword_document format.

Value

R Markdown output format to pass torender

Author(s)

Max Gordon

Examples

# Possible yaml configuration at the top of the Rmd doc## Not run: ---title: "Test"author: "Max Gordon"output:  Gmisc::docx_document---## End(Not run)

An alternative to the internaldo.call

Description

Thedo.call can be somewhat slow, especially when workingwith large objects. This function is based upon the suggestions from HadleyWickham on the R mailing list.Also thanks toTommy at StackOverflow forsuggestinghow to handle double and triple colon operators,::, furtherenhancing the function.

Usage

fastDoCall(what, args, quote = FALSE, envir = parent.frame())

Arguments

what

either a function or a non-empty character string naming thefunction to be called.

args

alist of arguments to the function call. Thenames attribute ofargs gives the argument names.

quote

a logical value indicating whether to quote thearguments.

envir

an environment within which to evaluate the call. Thiswill be most useful ifwhat is a character string andthe arguments are symbols or quoted expressions.

Note

While the function attempts to do most of whatdo.callcan it has limitations. It can currently not parse the example code from theoriginal function:do.call(paste, list(as.name("A"), as.name("B")), quote = TRUE)and the functionality ofquote has not been thoroughly tested.

Examples

fastDoCall("complex", list(imaginary = 1:3))## if we already have a list (e.g. a data frame)## we need c() to add further argumentstmp <- expand.grid(letters[1:2], 1:3, c("+", "-"))fastDoCall("paste", c(tmp, sep = ""))## examples of where objects will be found.A <- 2f <- function(x) print(x^2)env <- new.env()assign("A", 10, envir = env)assign("f", f, envir = env)f <- function(x) print(x)f(A)                                      # 2fastDoCall("f", list(A))                     # 2fastDoCall("f", list(A), envir = env)        # 4fastDoCall(f, list(A), envir = env)          # 2fastDoCall("f", list(quote(A)), envir = env) # 100fastDoCall(f, list(quote(A)), envir = env)   # 10fastDoCall("f", list(as.name("A")), envir = env) # 100eval(call("f", A))                      # 2eval(call("f", quote(A)))               # 2eval(call("f", A), envir = env)         # 4eval(call("f", quote(A)), envir = env)  # 100

Adds a figure caption number

Description

The function relies onoptions("fig_caption_no")in order to keep track of the last number. Ifyou want to force the caption function to skipcaptions while still using it in the knitr fig.cap optionthen simply setoptions(fig_caption_no = FALSE)

Usage

figCapNo(  str,  roman = getOption("fig_caption_no_roman", default = FALSE),  sprintf_str = getOption("fig_caption_no_sprintf", default = "Fig. %s: %s"))

Arguments

str

The string that is to be prepended with string

roman

Whether or not to use roman numbers insteadof Arabic. Can also be set throughoptions(fig_caption_no_roman = TRUE)

sprintf_str

Ansprintf formattedstring where the first argument is reserved for the stringgenerated by the counter and the second one is for the captiontext. Can also be set throughoptions(fig_caption_no_sprintf = TRUE)

See Also

Other figure caption functions:figCapNoLast(),figCapNoNext()

Examples

## Not run: ```{r, fig.cap = pigCapNo("My nice plot")}plot(1:10 + rnorm(10), 1:10)```## End(Not run)org_opts <- options(fig_caption_no = 2,                    fig_caption_no_sprintf = "Figure %s: %s")figCapNo("A plot with caption number = 3")org_opts <- options(fig_caption_no = TRUE)figCapNo("A plot with caption number = 1")# Use default settingoptions(fig_caption_no_sprintf = NULL)figCapNo("A plot with caption number = 2")# Return the original settingsoptions(org_opts)

Gets the last figure caption number

Description

The function relies onoptions("fig_caption_no")in order to keep track of the last number.

Usage

figCapNoLast(roman = getOption("fig_caption_no_roman", FALSE))

Arguments

roman

Whether or not to use roman numbers insteadof Arabic. Can also be set throughoptions(fig_caption_no_roman = TRUE)

See Also

Other figure caption functions:figCapNo(),figCapNoNext()

Examples

org_opts <- options(fig_caption_no = 1)figCapNoLast()options(org_opts)

Gets the next figure caption number

Description

The function relies onoptions("fig_caption_no")in order to keep track of the last number.

Usage

figCapNoNext(roman = getOption("fig_caption_no_roman", default = FALSE))

Arguments

roman

Whether or not to use roman numbers insteadof Arabic. Can also be set throughoptions(fig_caption_no_roman = TRUE)

See Also

Other figure caption functions:figCapNo(),figCapNoLast()

Examples

org_opts <- options(fig_caption_no = 1)figCapNoNext()options(org_opts)

Translates "npc" widths into absolute units

Description

The "npc"unit is not absolute, i.e.it depends on the relation between height and width withinthe current viewport. We therefore need to change these valuesto the value most likely intended. This is believed to be themain direction of the arrow as specified by the first and lastbezier control pointsx andy.

Usage

getAbsoluteWidth(w, default.units, x = x, y = y)

Arguments

w

The width that is to be changed

default.units

A string indicating the default units to useifx oryare only given as numeric vectors.

x

A numeric vector or unit object specifying x-locations ofspline control points.

y

A numeric vector or unit object specifying y-locations ofspline control points.

Value

The width transformed into aunit of "mm"


Gets the bezier points adjusted for an arrow

Description

Gets the bezier points adjusted for an arrow

Usage

getBezierAdj4Arrw(x, y, arrow_length, length_out = 100)

Arguments

x

The x start and end points

y

The spline control points

arrow_length

The desired length of the arrow

length_out

Increases the resolution for the final bezierpoints, i.e. generating more fine-grained intervals

Value

list


Creating of description statistics

Description

A function that returns a description statistic that can be usedfor creating a publication "table 1" when you want it by groups.The function identifies if the variable is a continuous, binaryor a factored variable. The format is inspired by NEJM, Lancet &BMJ.

Usage

getDescriptionStatsBy(  x,  ...,  by,  digits = 1,  digits.nonzero = NA,  html = TRUE,  numbers_first = TRUE,  statistics = FALSE,  statistics.sig_lim = 10^-4,  statistics.two_dec_lim = 10^-2,  statistics.suppress_warnings = TRUE,  useNA = c("ifany", "no", "always"),  useNA.digits = digits,  continuous_fn = describeMean,  prop_fn = describeProp,  factor_fn = describeFactors,  show_all_values = FALSE,  hrzl_prop = FALSE,  add_total_col,  total_col_show_perc = TRUE,  use_units = FALSE,  units_column_name = "Units",  default_ref = NULL,  NEJMstyle = FALSE,  percentage_sign = TRUE,  header_count = NULL,  missing_value = "-",  names_of_missing = NULL)## S3 method for class 'Gmisc_getDescriptionStatsBy'htmlTable(x, ...)## S3 method for class 'Gmisc_getDescriptionStatsBy'print(x, ...)## S3 method for class 'Gmisc_getDescriptionStatsBy'knit_print(x, ...)## S3 method for class 'Gmisc_getDescriptionStatsBy'length(x)

Arguments

x

If a data.frame it will be used as the data source for the variables in the... parameter.If it is a single variable it will be the core value that want the statistics for.In the print this is equivalent to the output of this function.

...

The variables that you want you statistic for. In the print all thes parametersare passed on as [htmlTable::htmlTable] arguments.

by

The variable that you want to split into different columns

digits

The number of decimals used

digits.nonzero

The number of decimals used for values that are close to zero

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

numbers_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().

statistics

Add statistics, fisher test for proportions and Wilcoxonfor continuous variables. See details below for more customization.

statistics.sig_lim

The significance limit for < sign, i.e. p-value 0.0000312should be < 0.0001 with the default setting.

statistics.two_dec_lim

The limit for showing two decimals. E.g.the p-value may be 0.056 and we may want to keep the two decimals in orderto emphasize the proximity to the all-mighty 0.05 p-value and set this to10^-2. This allows that a value of 0.0056 is rounded to 0.006 and thismakes intuitive sense as the 0.0056 level as this is well belowthe 0.05 value and thus not as interesting to know the exact proximity to0.05.Disclaimer: The 0.05-limit is really silly and debated, unfortunatelyit remains a standard and this package tries to adapt to the current standards in orderto limit publication associated issues.

statistics.suppress_warnings

Hide warnings from the statistics function.

useNA

This indicates if missing should be added as a separaterow below all other. Seetable foruseNA-options.Note: defaults to ifany and not "no" astable does.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

continuous_fn

The method to describe continuous variables. Thedefault isdescribeMean.

prop_fn

The method used to describe proportions, seedescribeProp.

factor_fn

The method used to describe factors, seedescribeFactors.

show_all_values

Show all values in proportions. For factors with only two valuesit is most sane to only show one option as the other one will just be a complementto the first, i.e. we want to convey a proportion. For instance sex - if you knowgender then automatically you know the distribution of the other sex as it's 100 % - other %.To choose which one you want to show then set thedefault_ref parameter.

hrzl_prop

This is default FALSE and indicatesthat the proportions are to be interpreted in a vertical manner.If we want the data to be horizontal, i.e. the total should be shownand then how these differ in the different groups then set this to TRUE.

add_total_col

This adds a total column to the resulting table.You can also specify if you want the total column "first" or "last"in the column order.

total_col_show_perc

This is by default true but ifrequested the percentages are suppressed as this sometimes may be confusing.

use_units

If the Hmisc package's units() function has been employedit may be interesting to have a column at the far right that indicates theunit measurement. If this column is specified then the total column willappear before the units (if specified as last). You can also set the value to"name" and the units will be added to the name as a parenthesis,e.g. Age (years).

units_column_name

The name of the units column. Used if use_units = TRUE

default_ref

The default reference when dealing with proportions. When using'dplyr' syntax ('tidyselect') you can specify a named vector/list for each column name.

NEJMstyle

Adds - no (%) at the end to proportions

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable.

header_count

Set toTRUE if you want to add a header count,e.g. Smoking; No. 25 observations, where there is a new line after thefactor name. If you want a different text for the second line you canspecifically use thesprintf formatting, e.g. "No. %s patients".

missing_value

Value that is substituted for empty cells. Defaults to "-"

names_of_missing

Optional character vector containing the names of returned statistics,in case all returned values for a givenby level are missing. Defaults to NULL

Value

Returnsmatrix if a single value was provided, otherwise alistof matrices with the class"Gmisc_getDescriptionStatsBy".

Customizing statistics

You can specify what function that you want for statistic by providing a functionthat takes two argumentsx andby and returns a p-value. There area few functions already prepared for this seegetPvalAnova,getPvalChiSqgetPvalFishergetPvalKruskalgetPvalWilcox.The default functions used aregetPvalFisher andgetPvalWilcox (unless the byargument has more than three unique levels where it defaults togetPvalAnova).

If you want the function to select functions depending on the type of inputyou can provide a list with the names'continuous','proportion','factor' andthe function will choose accordingly. If you fail to define a certain categoryit will default to the above.

You can also use a custom function that returns a string with the attribute'colname'set that will be appended to the results instead of the p-value column.

See Also

Other descriptive functions:describeFactors(),describeMean(),describeMedian(),describeProp(),getPvalWilcox()

Examples

library(magrittr)library(dplyr)library(htmlTable)data(mtcars)mtcars %<>%  mutate(am = factor(am, levels = 0:1, labels = c("Automatic", "Manual")),         vs = factor(vs, levels = 0:1, labels = c("V-shaped", "straight")),         drat_prop = drat > median(drat),         drat_prop = factor(drat_prop,                            levels = c(FALSE, TRUE),                            labels = c("High ratio", "Low ratio")),         carb_prop = carb > 2,         carb_prop = factor(carb_prop,                            levels = c(FALSE, TRUE),                            labels = c("&le; 2", "&gt; 2")),         across(c(gear, carb, cyl), factor))# A simple bare-bone examplemtcars %>%  getDescriptionStatsBy(`Miles per gallon` = mpg,                        Weight = wt,                        `Carborators &le; 2` = carb_prop,                        by = am) %>%  htmlTable(caption  = "Basic continuous stats from the mtcars dataset")invisible(readline(prompt = "Press [enter] to continue"))# For labeling & units we use set_column_labels/set_column_unit that use# the Hmisc package annotation functionsmtcars %<>%  set_column_labels(am = "Transmission",                    mpg = "Gas",                    wt = "Weight",                    gear = "Gears",                    disp = "Displacement",                    vs = "Engine type",                    drat_prop = "Rear axel ratio",                    carb_prop = "Carburetors") %>%  set_column_units(mpg = "Miles/(US) gallon",                   wt = "10<sup>3</sup> lbs",                   disp = "cu.in.")mtcars %>%  getDescriptionStatsBy(mpg,                        wt,                        `Gear&dagger;` = gear,                        drat_prop,                        carb_prop,                        vs,                        by = am,                        header_count = TRUE,                        use_units = TRUE,                        show_all_values = TRUE)  %>%  addHtmlTableStyle(pos.caption = "bottom") %>%  htmlTable(caption  = "Stats from the mtcars dataset",            tfoot = "&dagger; Number of forward gears")invisible(readline(prompt = "Press [enter] to continue"))# Using the default parameter we canmtcars %>%  getDescriptionStatsBy(mpg,                        wt,                        `Gear&dagger;` = gear,                        drat_prop,                        carb_prop,                        vs,                        by = am,                        header_count = TRUE,                        use_units = TRUE,                        default_ref = c(drat_prop = "Low ratio",                                        carb_prop = "&gt; 2"))  %>%  addHtmlTableStyle(pos.caption = "bottom") %>%  htmlTable(caption  = "Stats from the mtcars dataset",            tfoot = "&dagger; Number of forward gears")invisible(readline(prompt = "Press [enter] to continue"))# We can also use liststll <- list()tll[["Gear (3 to 5)"]] <- getDescriptionStatsBy(mtcars$gear, mtcars$am)tll <- c(tll,         list(getDescriptionStatsBy(mtcars$disp, mtcars$am)))mergeDesc(tll,          htmlTable_args = list(caption  = "Factored variables")) %>%  htmlTable::addHtmlTableStyle(css.rgroup = "")invisible(readline(prompt = "Press [enter] to continue"))tl_no_units <- list()tl_no_units[["Gas (mile/gallons)"]] <-  getDescriptionStatsBy(mtcars$mpg, mtcars$am,                        header_count = TRUE)tl_no_units[["Weight (10<sup>3</sup> kg)"]] <-  getDescriptionStatsBy(mtcars$wt, mtcars$am,                        header_count = TRUE)mergeDesc(tl_no_units,          tll) %>%  htmlTable::addHtmlTableStyle(css.rgroup = "")invisible(readline(prompt = "Press [enter] to continue"))# Other settingsmtcars$mpg[sample(1:NROW(mtcars), size = 5)] <- NAgetDescriptionStatsBy(mtcars$mpg,                      mtcars$am,                      statistics = TRUE)invisible(readline(prompt = "Press [enter] to continue"))# Do the horizontal versiongetDescriptionStatsBy(mtcars$gear,                      mtcars$am,                      statistics = TRUE,                      hrzl_prop = TRUE)invisible(readline(prompt = "Press [enter] to continue"))mtcars$wt_with_missing <- mtcars$wtmtcars$wt_with_missing[sample(1:NROW(mtcars), size = 8)] <- NAgetDescriptionStatsBy(mtcars$wt_with_missing, mtcars$am, statistics = TRUE,                      hrzl_prop = TRUE, total_col_show_perc = FALSE)invisible(readline(prompt = "Press [enter] to continue"))## Not run:   ## There is also a LaTeX wrapper  tll <- list(    getDescriptionStatsBy(mtcars$gear, mtcars$am),    getDescriptionStatsBy(mtcars$col, mtcars$am))  latex(mergeDesc(tll),        caption  = "Factored variables",        file = "")## End(Not run)

Gets grid value

Description

Returns the raw value in units if the provided is of type unit elseit returns the default unit.

Usage

getGridVal(x, default.units, axisTo = "x")

Arguments

x

Value

default.units

The unit type

axisTo

The axis that is used, useful for "npc" wherethere is a big difference in height and width

Value

float


P-value extractors forgetDescriptionStatsBy

Description

These functions are the base functions for getting the descriptionp-values. You can provide your own functions but all functions shouldtake two arguments and return a p-value (numeric, non-formatted)

Usage

getPvalWilcox(x, by)getPvalAnova(x, by)getPvalFisher(x, by)getPvalChiSq(x, by)getPvalKruskal(x, by)

Arguments

x

The main variable of interest

by

The variable for the stratification

Value

numeric Returns the p-value from that particular test

getPvalWilcox

Performs a two-sample two-sided Wilcoxon test (also known as the Mann-Whitney test),seewilcox.test.

getPvalAnova

Performs a standard Analysis of Variance modelthroughanova(lm(x ~ by))

getPvalFisher

Performs Fisher's exact test through thefisher.test.

getPvalChiSq

Performs a standard Chi-Squares analysisthroughchisq.test

getPvalKruskal

Performs a Kruskal-Wallis rank sum testthroughkruskal.test

See Also

Other descriptive functions:describeFactors(),describeMean(),describeMedian(),describeProp(),getDescriptionStatsBy()

Examples

set.seed(123)getPvalFisher(  sample(letters[1:3], size = 100, replace = TRUE),  sample(LETTERS[1:3], size = 100, replace = TRUE))getPvalWilcox(  rnorm(100),  sample(LETTERS[1:2], size = 100, replace = TRUE))

Gets the maximum contributor variables from svd()

Description

This function is inspired by Jeff Leeks Data Analysis course wherehe suggests that one way to use thesvd is to lookat the most influential rows for first columns in the V matrix.

Usage

getSvdMostInfluential(  mtrx,  quantile,  similarity_threshold,  plot_selection = TRUE,  plot_threshold = 0.05,  varnames = NULL)

Arguments

mtrx

A matrix or data frame with the variables. Note: if it contains missingvariables make sure to impute prior to this function as thesvd can'thandle missing values.

quantile

The SVD D-matrix gives an estimate for the amount that is explained.This parameter is used for selecting the columns that have that quantileof explanation.

similarity_threshold

A quantile for how close other variables have to be in value tomaximum contributor of that particular column. If you only want the maximum valuethen set this value to 1.

plot_selection

As this is all about variable exploring it is often interestingto see how the variables were distributed among the vectors

plot_threshold

The threshold of the plotted bars, measured aspercent explained by the D-matrix. By default it is set to 0.05.

varnames

A vector with alternative names to the colnames

Details

This function expands on that idea and adds the option of choosingmore than just the most contributing variable for each row. For instancetwo variables may have a major impact on a certain component where the secondvariable has 95important in that particular component it makes sense to include itin the selection.

It is of course useful when you have many continuous variables and you wantto determine a subgroup to look at, i.e. finding the needle in the haystack.

Value

Returns a list with vector with the column numbersthat were picked in the "most_influential" variable and thesvd caluclation in the "svd"

Examples

org_par <- par(ask = TRUE)set.seed(1345)# Simulate data with a patterndataMatrix <- matrix(rnorm(15 * 160), ncol = 15)colnames(dataMatrix) <- c(    paste("Pos.3:", 1:3, sep = " #"),    paste("Neg.Decr:", 4:6, sep = " #"),    paste("No pattern:", 7:8, sep = " #"),    paste("Pos.Incr:", 9:11, sep = " #"),    paste("No pattern:", 12:15, sep = " #"))for (i in 1:nrow(dataMatrix)) {  # flip a coin  coinFlip1 <- rbinom(1, size = 1, prob = 0.5)  coinFlip2 <- rbinom(1, size = 1, prob = 0.5)  coinFlip3 <- rbinom(1, size = 1, prob = 0.5)  # if coin is heads add a common pattern to that row  if (coinFlip1) {    cols <- grep("Pos.3", colnames(dataMatrix))    dataMatrix[i, cols] <- dataMatrix[i, cols] + 3  }  if (coinFlip2) {    cols <- grep("Neg.Decr", colnames(dataMatrix))    dataMatrix[i, cols] <- dataMatrix[i, cols] - seq(from = 5, to = 15, length.out = length(cols))  }  if (coinFlip3) {    cols <- grep("Pos.Incr", colnames(dataMatrix))    dataMatrix[i, cols] <- dataMatrix[i, cols] + seq(from = 3, to = 15, length.out = length(cols))  }}# Illustrate dataheatmap(dataMatrix, Colv = NA, Rowv = NA, margins = c(7, 2), labRow = "")svd_out <- svd(scale(dataMatrix))library(lattice)b_clr <- c("steelblue", "darkred")key <- simpleKey(  rectangles = TRUE, space = "top", points = FALSE,  text = c("Positive", "Negative"))key$rectangles$col <- b_clrb1 <- barchart(as.table(svd_out$v[, 1]),               main = "First column",               horizontal = FALSE, col = ifelse(svd_out$v[, 1] > 0,                                                b_clr[1], b_clr[2]               ),               ylab = "Impact value",               scales = list(x = list(rot = 55, labels = colnames(dataMatrix), cex = 1.1)),               key = key)b2 <- barchart(as.table(svd_out$v[, 2]),               main = "Second column",               horizontal = FALSE, col = ifelse(svd_out$v[, 2] > 0,                                                b_clr[1], b_clr[2]               ),               ylab = "Impact value",               scales = list(x = list(rot = 55, labels = colnames(dataMatrix), cex = 1.1)),               key = key)b3 <- barchart(as.table(svd_out$v[, 3]),               main = "Third column",               horizontal = FALSE, col = ifelse(svd_out$v[, 3] > 0,                                                b_clr[1], b_clr[2]               ),               ylab = "Impact value",               scales = list(x = list(rot = 55, labels = colnames(dataMatrix), cex = 1.1)),               key = key)b4 <- barchart(as.table(svd_out$v[, 4]),               main = "Fourth column",               horizontal = FALSE, col = ifelse(svd_out$v[, 4] > 0,                                                b_clr[1], b_clr[2]               ),               ylab = "Impact value",               scales = list(x = list(rot = 55, labels = colnames(dataMatrix), cex = 1.1)),               key = key)# Note that the fourth has the no pattern columns as the# chosen pattern, probably partly because of the previous# patterns already had been identifiedprint(b1, position = c(0, 0.5, .5, 1), more = TRUE)print(b2, position = c(0.5, 0.5, 1, 1), more = TRUE)print(b3, position = c(0, 0, .5, .5), more = TRUE)print(b4, position = c(0.5, 0, 1, .5))# Let's look at how well the SVD identifies# the most influential columnsgetSvdMostInfluential(dataMatrix,                      quantile = .8,                      similarity_threshold = .9,                      plot_threshold = .05,                      plot_selection = TRUE)par(org_par)

Gets an angle

Description

Uses a vector to get an angle byatan2.

Usage

getVectorAngle(x, y, x_origo = NA, y_origo = NA)

Arguments

x

The x point of the vector

y

The y point of the vector

x_origo

The x origin if other than 0

y_origo

The y origin if other than 0

Value

angle in radians (seeatan2)


Generates a generalized Bézier line

Description

This is a general form of bezier line that can be used for cubic, quadratic,and more advanced Bézier lines.

Usage

gnrlBezierPoints(ctrl_points, length_out = 100L)

Arguments

ctrl_points

The ctrl_points for the bezier control points. This shouldeither be amatrix or adata.frame.

length_out

The length of the return points, i.e. how finedetailed the points should be.

Examples

library(grid)grid.newpage()l <- gnrlBezierPoints(data.frame(x = c(.1, -.1, .7, 1, 1, 0.1),                                 y = c(.9, 0, 1, .8, .4, .1)),                      length_out = 100)grid.lines(l[,1], l[,2], gp=gpar(col="#550000", lwd = 4))out_sizes <- 4:20clrs <- colorRampPalette(c("orange", "darkblue"))(length(out_sizes))for (i in out_sizes){   l <- gnrlBezierPoints(data.frame(x = c(.1, -.1, .7, 1, 1, 0.1),                                    y = c(.9, 0, 1, .8, .4, .1)),                         length_out = i)   grid.lines(l[,1], l[,2],   gp=gpar(col=clrs[which(i == out_sizes)]))}

An R alternative to the lodashhas in JavaScript

Description

This is a handy function for checking if item exist in a nested structure

Usage

has(sourceList, path)

Arguments

sourceList

Thelist()/c() that is to be searched for the element

path

A string that can be separated by [,] or ., the string"elementname1.1.elementname"the validity of the path - it only separates and tries to address that element with '[[]]'.

Value

Returns a boolean.

See Also

Other lodash similar functions:retrieve()

Examples

has(list(a = list(b = 1)), "a.b")

Insert a row into a matrix

Description

Inserts a row and keeps the attributescopyAllNewAttributes

Usage

insertRowAndKeepAttr(m, r, v = NA, rName = "")

Arguments

m

matrix

r

row number where the new row should be inserted

v

optional values for the new row

rName

optional character string: the name of the new row.

Value

matrix Returns a matrix with one more row than the provided matrixm

Author(s)

Max Gordon, Arne Henningsen

Examples

test <- matrix(1:4, ncol = 2)attr(test, "wow") <- 1000test <- insertRowAndKeepAttr(test, 2)print(attr(test, "wow"))

Just a simple help with interpreting the radians

Description

Just a simple help with interpreting the radians

Usage

isHorizontal(angle_radian)

Arguments

angle_radian

The angle in radians

Value

boolean


A wrapper around thehtmlTable/latex function

Description

Calls thehtmlTable/latex after extracting thergroup/n.rgroup arguments.

Usage

## S3 method for class 'descMrg'latex(object, ...)## S3 method for class 'descMrg'htmlTable(x, ...)## S3 method for class 'descMrg'print(x, ...)## S3 method for class 'descMrg'knit_print(x, ...)

Arguments

object

ThemergeDesc object

...

Passed ontohtmlTable/latex


Prepares a matrix forhtmlTable from a list

Description

By putting all the output from thegetDescriptionStatsByinto a list, naming each element that we want in anrgroup we canautomatically merge everything and create an object ready for thehtmlTable.

Usage

mergeDesc(..., htmlTable_args = list())

Arguments

...

One or more elements coming fromgetDescriptionStatsBy.You can also provide pure output from thegetDescriptionStatsBy functionand have the function merge this together with the... argument.Note that all elements must have the sameby argument or youwill not be able to merge it into a list.

htmlTable_args

Any arguments that should be passed tohtmlTable function. The default is to removeany css formatting for thergroup.

Value

matrix Returns a matrix object of class descList

Thergroup value

The value for thergroup is by default the name of the list element. If you havepassed a list without a name for that particular element or if you have passed amatrix it will look for a label set by theHmisc::label function.For those elements that have only one row norgroup is set, and the naming sequenceis the same as above but with an additionalrownames if the previoustwo turn out empty. All this behavior is exemplified in the example.

Thergroup value can be overridden by simply specifying a customrgroup whencalling thehtmlTable function.

Thecolnames of the matrix

The function chooses thecolnames from the first element inthetlist.

Examples

library(magrittr)library(dplyr)library(htmlTable)data(mtcars)mtcars %<>%  mutate(am = factor(am, levels = 0:1, labels = c("Automatic", "Manual")),         vs = factor(vs, levels = 0:1, labels = c("V-shaped", "straight")),         drat_prop = drat > median(drat),         drat_prop = factor(drat_prop,                            levels = c(FALSE, TRUE),                            labels = c("High ratio", "Low ratio")),         carb_prop = carb > 2,         carb_prop = factor(carb_prop,                            levels = c(FALSE, TRUE),                            labels = c("&le; 2", "&gt; 2")),         across(c(gear, carb, cyl), factor))# A simple bare-bone examplemtcars %>%  getDescriptionStatsBy(`Miles per gallon` = mpg,                        Weight = wt,                        `Carborators &le; 2` = carb_prop,                        by = am) %>%  htmlTable(caption  = "Basic continuous stats from the mtcars dataset")invisible(readline(prompt = "Press [enter] to continue"))# For labeling & units we use set_column_labels/set_column_unit that use# the Hmisc package annotation functionsmtcars %<>%  set_column_labels(am = "Transmission",                    mpg = "Gas",                    wt = "Weight",                    gear = "Gears",                    disp = "Displacement",                    vs = "Engine type",                    drat_prop = "Rear axel ratio",                    carb_prop = "Carburetors") %>%  set_column_units(mpg = "Miles/(US) gallon",                   wt = "10<sup>3</sup> lbs",                   disp = "cu.in.")mtcars %>%  getDescriptionStatsBy(mpg,                        wt,                        `Gear&dagger;` = gear,                        drat_prop,                        carb_prop,                        vs,                        by = am,                        header_count = TRUE,                        use_units = TRUE,                        show_all_values = TRUE)  %>%  addHtmlTableStyle(pos.caption = "bottom") %>%  htmlTable(caption  = "Stats from the mtcars dataset",            tfoot = "&dagger; Number of forward gears")invisible(readline(prompt = "Press [enter] to continue"))# Using the default parameter we canmtcars %>%  getDescriptionStatsBy(mpg,                        wt,                        `Gear&dagger;` = gear,                        drat_prop,                        carb_prop,                        vs,                        by = am,                        header_count = TRUE,                        use_units = TRUE,                        default_ref = c(drat_prop = "Low ratio",                                        carb_prop = "&gt; 2"))  %>%  addHtmlTableStyle(pos.caption = "bottom") %>%  htmlTable(caption  = "Stats from the mtcars dataset",            tfoot = "&dagger; Number of forward gears")invisible(readline(prompt = "Press [enter] to continue"))# We can also use liststll <- list()tll[["Gear (3 to 5)"]] <- getDescriptionStatsBy(mtcars$gear, mtcars$am)tll <- c(tll,         list(getDescriptionStatsBy(mtcars$disp, mtcars$am)))mergeDesc(tll,          htmlTable_args = list(caption  = "Factored variables")) %>%  htmlTable::addHtmlTableStyle(css.rgroup = "")invisible(readline(prompt = "Press [enter] to continue"))tl_no_units <- list()tl_no_units[["Gas (mile/gallons)"]] <-  getDescriptionStatsBy(mtcars$mpg, mtcars$am,                        header_count = TRUE)tl_no_units[["Weight (10<sup>3</sup> kg)"]] <-  getDescriptionStatsBy(mtcars$wt, mtcars$am,                        header_count = TRUE)mergeDesc(tl_no_units,          tll) %>%  htmlTable::addHtmlTableStyle(css.rgroup = "")invisible(readline(prompt = "Press [enter] to continue"))# Other settingsmtcars$mpg[sample(1:NROW(mtcars), size = 5)] <- NAgetDescriptionStatsBy(mtcars$mpg,                      mtcars$am,                      statistics = TRUE)invisible(readline(prompt = "Press [enter] to continue"))# Do the horizontal versiongetDescriptionStatsBy(mtcars$gear,                      mtcars$am,                      statistics = TRUE,                      hrzl_prop = TRUE)invisible(readline(prompt = "Press [enter] to continue"))mtcars$wt_with_missing <- mtcars$wtmtcars$wt_with_missing[sample(1:NROW(mtcars), size = 8)] <- NAgetDescriptionStatsBy(mtcars$wt_with_missing, mtcars$am, statistics = TRUE,                      hrzl_prop = TRUE, total_col_show_perc = FALSE)invisible(readline(prompt = "Press [enter] to continue"))## Not run:   ## There is also a LaTeX wrapper  tll <- list(    getDescriptionStatsBy(mtcars$gear, mtcars$am),    getDescriptionStatsBy(mtcars$col, mtcars$am))  latex(mergeDesc(tll),        caption  = "Factored variables",        file = "")## End(Not run)

Merging of multiple lists

Description

The merge allows for a recursive componentwhere the lists are compared on the subelement.If one does not contain that element it will get NAin for those parameters.

Usage

mergeLists(  ...,  lapplyOutput = NULL,  sortNames = getOption("Gmisc.mergeList.sort", default = TRUE))

Arguments

...

Any number of lists that you want to merge

lapplyOutput

Thelapply function outputs a numberof lists and this is for specifically merging all of those.

sortNames

Set to false if you don't want the names to be sorted.This can also be done via the option 'Gmisc.mergeList.sort'.

Value

Returns a list with all the given lists.

Examples

v1 <- list("a" = c(1, 2), b = "test 1", sublist = list(one = 20:21, two = 21:22))v2 <- list("a" = c(3, 4), b = "test 2", sublist = list(one = 10:11, two = 11:12, three = 1:2))mergeLists(v1, v2)

A helper function for mergeLists that does the actual work.

Description

A helper function for mergeLists that does the actual work.

Usage

mergeLists_internal(o_element, n_element)

Arguments

o_element

Old element

n_element

New element to add to the old element

Value

list with the two merged


Move a boxGrob

Description

Moves aboxGrob/boxPropGrob by modifying it'sviewport.This can be useful if you want to create a series of boxes whose position are relativeto each other and depend on each box's width/height.

Usage

moveBox(  element,  x = NULL,  y = NULL,  space = c("absolute", "relative"),  just = NULL)

Arguments

element

AboxGrob/boxPropGrob object.

x

Aunit element or a numeric that can be converted to anpc unit object.

y

Aunit element or a numeric that can be converted to anpc unit object.

space

We can provideabsolute that confers the box absolute position within the parentviewport. Ifrelative the movement is related to the current position.

just

The justification of an argument as used byviewport some tiny differences:(1) you only want to change the justification in the vertical direction you can retain theexisting justification by usingNA, e.g.c(NA, 'top'), (2) if you specify only one stringand that string is eithertop orbottom it will assume vertical justification.

Value

The element with updated

See Also

Other flowchart components:align,boxGrob(),boxPropGrob(),connectGrob(),coords(),distance(),spread

Examples

library(grid)grid.newpage()box <- boxGrob("A simple box", x = .5, y = .8)moveBox(box, x = -.2, space = "relative")

A path join function

Description

This function joins strings into a valid path. It is a simple version of python'sos.path.join and fixes simple problems such as having/not having trailing /in each section.

Usage

pathJoin(...)

Arguments

...

A set of strings to join. Each may be a single string or a vector.If you provide vectors they can either be all of the same lengthor where there are two lengths where one is equal to 1.

Value

string A string with the merged path

Examples

pathJoin("my_base_path/helpers", "superfunction.R")# 'my_base_path/helpers/superfunction.R'base_dir <- "/home/tester/images"out <- data.frame(filename = c("file1.png", "file2.png", "file3.png")) |>  dplyr::mutate(full_path = pathJoin(base_dir, filename))

Add a p-value column to the results

Description

Add a p-value column to the results

Usage

prAddDescStats(  results,  x,  by,  statistics,  statistics.suppress_warnings,  statistics.sig_lim,  statistics.two_dec_lim,  html)

Arguments

results

The results that we want to add the column to

x

If a data.frame it will be used as the data source for the variables in the... parameter.If it is a single variable it will be the core value that want the statistics for.In the print this is equivalent to the output of this function.

by

The variable that you want to split into different columns

statistics

Add statistics, fisher test for proportions and Wilcoxonfor continuous variables. See details below for more customization.

statistics.suppress_warnings

Hide warnings from the statistics function.

statistics.sig_lim

The significance limit for < sign, i.e. p-value 0.0000312should be < 0.0001 with the default setting.

statistics.two_dec_lim

The limit for showing two decimals. E.g.the p-value may be 0.056 and we may want to keep the two decimals in orderto emphasize the proximity to the all-mighty 0.05 p-value and set this to10^-2. This allows that a value of 0.0056 is rounded to 0.006 and thismakes intuitive sense as the 0.0056 level as this is well belowthe 0.05 value and thus not as interesting to know the exact proximity to0.05.Disclaimer: The 0.05-limit is really silly and debated, unfortunatelyit remains a standard and this package tries to adapt to the current standards in orderto limit publication associated issues.

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

Value

results with added column


Add a units column to the results

Description

Add a units column to the results

Usage

prAddDescUnitColumn(results, x, use_units, units_column_name)

Arguments

results

The results that we want to add the column to

x

If a data.frame it will be used as the data source for the variables in the... parameter.If it is a single variable it will be the core value that want the statistics for.In the print this is equivalent to the output of this function.

use_units

If the Hmisc package's units() function has been employedit may be interesting to have a column at the far right that indicates theunit measurement. If this column is specified then the total column willappear before the units (if specified as last). You can also set the value to"name" and the units will be added to the name as a parenthesis,e.g. Age (years).

units_column_name

The name of the units column. Used if use_units = TRUE

Value

results with added column


Convert the by-list into a matrix compatible format

Description

Helper for [getDescriptionStatsBy] that fixes empty values in matrixso that they are compatible with the matrix

Usage

prAddEmptyVals(t, missing_value)

Arguments

t

Output from [prNumericDescs], [prPropDescs], or [prFactorDescs].

missing_value

Value that is substituted for empty cells. Defaults to "-"

Value

A fixed list


Add a total column to the results

Description

Add a total column to the results

Usage

prAddTotalDescColumn(  results,  x,  by,  numbers_first,  total_col_show_perc,  show_all_values,  useNA,  useNA.digits,  html,  digits,  continuous_fn,  factor_fn,  prop_fn,  percentage_sign,  default_ref,  header_count = NULL,  add_total_col)

Arguments

results

The results that we want to add the column to

x

If a data.frame it will be used as the data source for the variables in the... parameter.If it is a single variable it will be the core value that want the statistics for.In the print this is equivalent to the output of this function.

by

The variable that you want to split into different columns

numbers_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().

total_col_show_perc

This is by default true but ifrequested the percentages are suppressed as this sometimes may be confusing.

show_all_values

Show all values in proportions. For factors with only two valuesit is most sane to only show one option as the other one will just be a complementto the first, i.e. we want to convey a proportion. For instance sex - if you knowgender then automatically you know the distribution of the other sex as it's 100 % - other %.To choose which one you want to show then set thedefault_ref parameter.

useNA

This indicates if missing should be added as a separaterow below all other. Seetable foruseNA-options.Note: defaults to ifany and not "no" astable does.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

digits

The number of decimals used

continuous_fn

The method to describe continuous variables. Thedefault isdescribeMean.

factor_fn

The method used to describe factors, seedescribeFactors.

prop_fn

The method used to describe proportions, seedescribeProp.

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable.

default_ref

The default reference when dealing with proportions. When using'dplyr' syntax ('tidyselect') you can specify a named vector/list for each column name.

header_count

Set toTRUE if you want to add a header count,e.g. Smoking; No. 25 observations, where there is a new line after thefactor name. If you want a different text for the second line you canspecifically use thesprintf formatting, e.g. "No. %s patients".

add_total_col

This adds a total column to the resulting table.You can also specify if you want the total column "first" or "last"in the column order.

Value

results with added column


Add a sub-label toboxPropGrob

Description

Add a sub-label toboxPropGrob

Usage

prBuildSubLabel(label, prop, txt_gp, side = c("left", "right"))

Arguments

label

The text of the label

prop

The proportion

txt_gp

The style as defined bygpar()

side

The side that the label belongs to

Value

AtextGrob with he additional attributeswidth andheight.


Fixes the caption for elements without caption

Description

Fixes the caption for elements without caption

Usage

prCaptionFix(outFile)

Arguments

outFile

The name of the file

Value

outFile The name of the file


Converts an object to coordinates

Description

Sometimes we have an object that can be either a box,a coprdinate, a unit or a numerical value and all wewant is alist of coordinates that we can use forcalculating distance, alignment and other things.

Usage

prConvert2Coords(obj)

Arguments

obj

AboxGrob,boxPropGrob,coords output,unit or a number ranging tobe converted to anpcunit

Value

Alist with all the points thatcoords returns


Creates coordinates for box

Description

Creates coordinates for box

Usage

prCreateBoxCoordinates(viewport_data, extra_coordinate_functions = NULL)

Arguments

viewport_data

The arguments that will be used for generating theviewport

extra_coordinate_functions

A list with named functions if we want additionalparameters

Value

list of classcoords


A helper function for the description stats

Description

A helper function for the description stats

Usage

prDescGetAndValidateDefaultRef(x, default_ref)

Arguments

x

The variable of interest with the levels

default_ref

The default reference, either first,the level name or a number within the levels. If left outit defaults to the first value.

Value

integer The level number of interest


Helper to [getDescriptionStatsBy()]

Description

Helper to [getDescriptionStatsBy()]

Usage

prFactorDescs(  x,  by,  factor_fn,  hrzl_prop,  html,  digits,  digits.nonzero,  numbers_first,  useNA,  useNA.digits,  percentage_sign,  missing_value,  names_of_missing)

Arguments

x

If a data.frame it will be used as the data source for the variables in the... parameter.If it is a single variable it will be the core value that want the statistics for.In the print this is equivalent to the output of this function.

by

The variable that you want to split into different columns

factor_fn

The method used to describe factors, seedescribeFactors.

hrzl_prop

This is default FALSE and indicatesthat the proportions are to be interpreted in a vertical manner.If we want the data to be horizontal, i.e. the total should be shownand then how these differ in the different groups then set this to TRUE.

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

digits

The number of decimals used

digits.nonzero

The number of decimals used for values that are close to zero

numbers_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().

useNA

This indicates if missing should be added as a separaterow below all other. Seetable foruseNA-options.Note: defaults to ifany and not "no" astable does.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable.

missing_value

Value that is substituted for empty cells. Defaults to "-"

names_of_missing

Optional character vector containing the names of returned statistics,in case all returned values for a givenby level are missing. Defaults to NULL

Value

A [base::by] list


Fix rownames for descriptive results

Description

Helper for [getDescriptionStatsBy] that fixes row names

Usage

prFixDescRownames(results, t, name)

Arguments

results

A matrix with the results

t

The [base::by()] output

name

Name if row names are missing or the results is a single row

Value

The results with fixed names


Helper to ftp_document

Description

Helper to ftp_document

Usage

prFtpHeaderStyle(output_str, h1_style, other_h_style)

Arguments

output_str

The output string from readLines()

h1_style

You can choose any css style formatting here that youwant to be applied to all h1 elements. Note: this is only appliedif LibreOffice_adapt isTRUE.

other_h_style

This is the formatting applied to any otherh elements not included to the first. Note: this is only appliedif LibreOffice_adapt isTRUE.

Value

string


Changes lines for XML-conformity

Description

Changes lines for XML-conformity

Usage

prFtpOtherChanges(output_str)

Arguments

output_str

The input from readLines()

Value

string Returns with changes


Removes other unwanted lines

Description

Removes other unwanted lines

Usage

prFtpOtherRemoval(output_str)

Arguments

output_str

The input from readLines()

Value

string Returns without the unwanted lines


Removes the <script>*</scrip>

Description

Removes the <script>*</scrip>

Usage

prFtpScriptRemoval(output_str)

Arguments

output_str

The input from readLines()

Value

string Returns without the script elements


Retrieve basic description stats by header

Description

Helper for [getDescriptionStatsBy] that retrieves the basicheader names.

Usage

prGetDescHeader(by, html, header_count, already_table_format = FALSE)

Arguments

by

The variable that you want to split into different columns

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

header_count

Set toTRUE if you want to add a header count,e.g. Smoking; No. 25 observations, where there is a new line after thefactor name. If you want a different text for the second line you canspecifically use thesprintf formatting, e.g. "No. %s patients".

already_table_format

Just a boolean as we use this in the total column

Value

A vector with basic headers


Get statistics according to the type

Description

A simple function applied by thegetDescriptionStatsByfor the total column.

Usage

prGetStatistics(  x,  show_perc = FALSE,  html = TRUE,  digits = 1,  digits.nonzero = NA,  numbers_first = TRUE,  useNA = c("ifany", "no", "always"),  useNA.digits = digits,  show_all_values = FALSE,  continuous_fn = describeMean,  factor_fn = describeFactors,  prop_fn = factor_fn,  percentage_sign = TRUE,  default_ref = NULL)

Arguments

x

If a data.frame it will be used as the data source for the variables in the... parameter.If it is a single variable it will be the core value that want the statistics for.In the print this is equivalent to the output of this function.

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

digits

The number of decimals used

digits.nonzero

The number of decimals used for values that are close to zero

numbers_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().

useNA

This indicates if missing should be added as a separaterow below all other. Seetable foruseNA-options.Note: defaults to ifany and not "no" astable does.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

show_all_values

Show all values in proportions. For factors with only two valuesit is most sane to only show one option as the other one will just be a complementto the first, i.e. we want to convey a proportion. For instance sex - if you knowgender then automatically you know the distribution of the other sex as it's 100 % - other %.To choose which one you want to show then set thedefault_ref parameter.

continuous_fn

The method to describe continuous variables. Thedefault isdescribeMean.

factor_fn

The method used to describe factors, seedescribeFactors.

prop_fn

The method used to describe proportions, seedescribeProp.

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable.

default_ref

The default reference when dealing with proportions. When using'dplyr' syntax ('tidyselect') you can specify a named vector/list for each column name.

Value

A matrix or a vector depending on the settings


Just a simple acces to the gp$cex parameter

Description

Just a simple acces to the gp$cex parameter

Usage

prGetTextGrobCex(x)

Arguments

x

The text-grob of interest

Value

numeric The cex value, 1 if no cex was present


Adds a title to the plot

Description

Adds the title and generates a newmain viewport below the title

Usage

prGridPlotTitle(  title,  base_cex,  cex_mult = 1.2,  fontface = "bold",  space_below = NULL)

Arguments

title

The title as accepted bytextGrob

base_cex

The base cex used for the plot

cex_mult

The multiplier of the base - i.e. the increase of thetext size for the title as compared to the general

fontface

The type of fontface

space_below

The space below, defaults to 1/5 of the title height

Value

NULL The function does not return a value


Helper to [getDescriptionStatsBy()]

Description

Helper to [getDescriptionStatsBy()]

Usage

prNumericDescs(  x,  by,  hrzl_prop,  continuous_fn,  html,  digits,  digits.nonzero,  numbers_first,  useNA,  useNA.digits,  percentage_sign,  missing_value,  names_of_missing)

Arguments

x

If a data.frame it will be used as the data source for the variables in the... parameter.If it is a single variable it will be the core value that want the statistics for.In the print this is equivalent to the output of this function.

by

The variable that you want to split into different columns

hrzl_prop

This is default FALSE and indicatesthat the proportions are to be interpreted in a vertical manner.If we want the data to be horizontal, i.e. the total should be shownand then how these differ in the different groups then set this to TRUE.

continuous_fn

The method to describe continuous variables. Thedefault isdescribeMean.

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

digits

The number of decimals used

digits.nonzero

The number of decimals used for values that are close to zero

numbers_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().

useNA

This indicates if missing should be added as a separaterow below all other. Seetable foruseNA-options.Note: defaults to ifany and not "no" astable does.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable.

missing_value

Value that is substituted for empty cells. Defaults to "-"

names_of_missing

Optional character vector containing the names of returned statistics,in case all returned values for a givenby level are missing. Defaults to NULL

Value

A [base::by] list


Collapses a vector for throwing errors

Description

The function collapses a vector into an output useful when throwingerrors, e.g. 1:3 becomes '1', '2', '3'

Usage

prPasteVec(x)

Arguments

x

The vector


Helper to [getDescriptionStatsBy()]

Description

Helper to [getDescriptionStatsBy()]

Usage

prPropDescs(  x,  by,  name,  default_ref,  prop_fn,  html,  digits,  digits.nonzero,  numbers_first,  useNA,  useNA.digits,  percentage_sign,  missing_value,  names_of_missing,  NEJMstyle)

Arguments

x

If a data.frame it will be used as the data source for the variables in the... parameter.If it is a single variable it will be the core value that want the statistics for.In the print this is equivalent to the output of this function.

by

The variable that you want to split into different columns

name

The name of the row

default_ref

The default reference when dealing with proportions. When using'dplyr' syntax ('tidyselect') you can specify a named vector/list for each column name.

prop_fn

The method used to describe proportions, seedescribeProp.

html

If HTML compatible output should be used. IfFALSEit outputs LaTeX formatting

digits

The number of decimals used

digits.nonzero

The number of decimals used for values that are close to zero

numbers_first

If the number should be given or if the percentageshould be presented first. The second is encapsulated in parentheses ().

useNA

This indicates if missing should be added as a separaterow below all other. Seetable foruseNA-options.Note: defaults to ifany and not "no" astable does.

useNA.digits

The number of digits to use for themissing percentage, defaults to the overalldigits.

percentage_sign

If you want to suppress the percentage sign youcan set this variable to FALSE. You can also choose something else thatthe default % if you so wish by setting this variable.

missing_value

Value that is substituted for empty cells. Defaults to "-"

names_of_missing

Optional character vector containing the names of returned statistics,in case all returned values for a givenby level are missing. Defaults to NULL

NEJMstyle

Adds - no (%) at the end to proportions

Value

A [base::by] list


Pushes viewport with margins

Description

Agrid.layout object is used togenerate the margins. A second viewport selecting themid-row/col is used to create the effect of margins

Usage

prPushMarginViewport(bottom, left, top, right, name = "margin")

Arguments

bottom

The margin object, either in npc or aunit object,or a vector of 4 if you want the same margins allover.

left

The margin object, either in npc or aunit object.

top

The margin object, either in npc or aunit object

right

The margin object, either in npc or aunit object

name

The name of the last viewport

Value

2 - the number of pushed viewports


Updates the css max-width

Description

Reads the file, changes the max-widthfor the body element.

Usage

prSetMaxWidth(max_width, css_file)

Arguments

max_width

The new max-width css setting

css_file

The CSS file name

Value

string The file name


Finds the matching colors for the new addition based on the original setof colors

Description

Finds the matching colors for the new addition based on the original setof colors

Usage

prTcMatchClr(add, org, no_cols, no_rows, is3D)

Arguments

add

The colors that we want to add

org

The original colors

no_cols

The no. of columns in the transition matrix

no_rows

All the row counts in the transition plot

is3D

Whether the transition matrix has 3 dimensions

Value

A list with colors that is appropriate for the transition object


Plots the arrows within a single transition set

Description

Plots the arrows within a single transition set

Usage

prTcPlotArrows(  trnstn_set,  widths,  type = c("simple", "gradient"),  clr,  rez,  origin_boxes,  target_boxes,  left_box_clrs,  add_width,  max_flow,  min_width,  max_width,  abs_arrow_width = FALSE,  clr_bar_subspace)

Arguments

trnstn_set

The set of transitions to plot

widths

The arrow widths

type

The type of arrow to be used

clr

The arrow colors (a matrix)

rez

The arrow resolution

origin_boxes

The origin boxes' positions to the left

target_boxes

The target boxes' positions to the right

left_box_clrs

The colors of the left side boxes

add_width

Adds a certain width - useful for background arrows

max_flow

The maximum flow if it is common for the entire image

min_width

The minimum line width

max_width

The maximum line width

abs_arrow_width

If the arrow width should be the same for all arrows


Plots a column of boxes

Description

Takes a set of box settings and plots them.

Usage

prTcPlotBoxColumn(  box_positions,  proportions,  fill,  txt,  txt_clr,  txt_gpar,  cex)

Arguments

box_positions

The box positions

proportions

The box vertical proportions (needed for the prop attribute)

fill

The fill colors of length equal to the proportions

txt

The texts of length equal to the proportions

txt_clr

The text colors of length equal to the proportions

txt_gpar

A list of gpar object for the text box

cex

The fontsize multiplier

Value

void


Checks and prepares colors

Description

The colors need to match the size of the transition matrixand therefore we need to have this input check. The output isalways a matrix of the exact same dimensions as the transitionmatrix.

Usage

prTcValidateAndPrepClr(value, no_cols, no_rows, is3D)

Arguments

value

The color values

no_cols

The no. of columns in the transition matrix

no_rows

All the row counts in the transition plot

is3D

Whether the transition matrix has 3 dimensions

Value

matrix Returns a matrix of the same size as thetransition matrix


Gets the box position

Description

Gets the box position

Usage

prTpGetBoxPositions(  no,  side,  transitions,  prop_start_sizes,  prop_end_sizes,  tot_spacing,  box_width)

Arguments

no

The box number

side

The right or left side

transitions

The flows to or from

prop_start_sizes

The size of the start boxes

prop_end_sizes

The size of the end boxes

tot_spacing

The proportion of the vertical space that is to be leftempty. It is then split evenly between the boxes.

box_width

The width of the box. By default the box is one fourth ofthe plot width.

Value

list(top, left, bottom, right, width, height)


Gets the color for the given box

Description

Gets the color for the given box

Usage

prTpGetBoxPropClr(clr, no_boxes, lengthOneOK = FALSE)

Arguments

clr

The color of the boxes, eithera matrix, a vector of length two, or a single color

no_boxes

The number of boxes

lengthOneOK

If it is ok to have only one color

Value

matrix With two columns and no_boxes rows.If function fails then returnNULL


Gets the text size for the box

Description

Gets the text size for the box

Usage

prTpGetBoxSizedTextGrob(  txt,  txt_clr,  txt_cex,  txt_gpar = NULL,  force_cex = FALSE,  ...)

Arguments

txt

The text

txt_clr

The color of the text

txt_cex

The font size

txt_gpar

The [grid::gpar()] object that is overridden with col & cex by other parameters

force_cex

If font size should be forced

...

Other options


Gets a set of colors or just one color

Description

Used in order to illustrate the mix between twoproportions in thetransitionPlot.

Usage

prTpGetColors(colors, proportion, space = NULL, no = 101)

Arguments

colors

A set of min. two colors that is usedforcolorRampPalette.

proportion

A proportion or a set of proportionsbetween 0 and 1. If you leave this out then the full colorspan will be returned.

space

If there is little or no differenceat the low/high proportions of the spectrum then itcan be of interest to focus the color change to the centerleaving the tails constant

no

The color resolution to use

Value

character The function can return both single colorsor multiple colors as character vector (seergb)


Plots the arrows

Description

Outputs all the arrows from a box row

Usage

prTpPlotArrows(  type,  box_row,  transition_flow,  max_flow,  min_lwd,  max_lwd,  clr,  box_clr,  transition_arrow_props,  prop_start_sizes,  prop_end_sizes,  tot_spacing,  box_width,  abs_arrow_width,  color_bar_subspace,  add_width = NA)

Arguments

type

The type of arrow used

box_row

Which box do the arrows originate from

max_flow

The largest transition flow

min_lwd

The minimum line width

max_lwd

The maximum line width

clr

The color of the line

box_clr

The color of the box

transition_arrow_props

The proportions of the different transitions ifavailable.

prop_start_sizes

The proportions to the left

prop_end_sizes

The proportions to the right

tot_spacing

Total spacing between boxes

box_width

The box width

color_bar_subspace

If there is little or no difference existsat the low/high proportions of the spectrum then itcan be of interest to focus the color change to the centerleaving the tails constant

add_width

Add a certain width

Value

void


Plots the box for the transition plot

Description

Plots the box for the transition plot

Usage

prTpPlotBox(  bx,  bx_txt,  fill,  txt_clr,  txt_gpar = NULL,  cex,  line_col,  lwd,  prop = NA)

Arguments

bx

A list with the x, y, height and width parameters

bx_txt

The box text

fill

The fill color

txt_clr

The text color

txt_gpar

The [grid::gpar()] object that is overridden with col & cex by other parameters

cex

The font size

line_col

The line color around the box

lwd

The line width

prop

Provide a proportion if the box should be split (0-1)

Value

void


Plot boxes and arrows

Description

Outputs all the boxes and arrow

Usage

prTpPlotBoxes(  overlap_order,  transition_flow,  no_boxes,  box_width,  tot_spacing,  txt,  cex,  txt_gpar = NULL,  prop_start_sizes,  prop_end_sizes,  box_prop,  lwd_prop_total = lwd_prop_total,  fill_start_clr,  fill_end_clr,  txt_start_clr,  txt_end_clr,  lwd = 2,  line_col = "#000000",  min_lwd,  max_lwd,  overlap_add_width,  overlap_bg_clr,  type_of_arrow,  abs_arrow_width,  arrow_clr,  transition_arrow_props,  color_bar_subspace,  plot_arrows = TRUE,  proportion = FALSE)

Arguments

overlap_order

The order from first->last for the lines. This means that the lastline will be on top while the first one will appear at the bottom. This should be providedas a vector.

transition_flow

This should be a matrix with the size of the transitions.The unit for each cell should be number of observations, row/column-proportionswill show incorrect sizes. The matrix needs to be square. The best way to generatethis matrix is probably just do atable(starting_state, end_state). The rowsrepresent the starting positions, while the columns the end positions. I.e. the firstrows third column is the number of observations that go from the first class to thethird class.

no_boxes

Number of boxes to plot

box_width

The width of the box. By default the box is one fourth ofthe plot width.

tot_spacing

The proportion of the vertical space that is to be leftempty. It is then split evenly between the boxes.

txt

The text

cex

The cexgpar of the text

txt_gpar

The [grid::gpar()] object that is overridden with col & cex by other parameters

prop_start_sizes

The proportion of the different boxesto the left

prop_end_sizes

The proportion of the different boxesto the right

box_prop

If you want the boxes to have proportions indicating some other factors then inputa matrix with quantiles for the proportions. Note the size must benrow(transition_flow) x 2.

lwd_prop_total

The width of the lines may be proportional to either theother flows from that box, or they may be related to all flows. This is a booleanparameter that is set to true by default, i.e. relating to all flows.

fill_start_clr

The color of the boxes to the left

fill_end_clr

The color of the boxes to the right

txt_start_clr

The text color of the start boxes. This can eitherbe a single value or a vector if you desire different colors for eachbox. If you specify box_prop then this has to be a 2 column matrix.

txt_end_clr

The text color of the end boxes. This can eitherbe a single value or a vector if you desire different colors for eachbox. If you specify box_prop then this has to be a 2 column matrix.

lwd

The line width

line_col

The color of the line

min_lwd

The minimum width of the line that we want to illustrate thetranisition with.

max_lwd

The maximum width of the line that we want to illustrate thetranisition with.

overlap_add_width

The width of the white cross-over line. You can specify this as a scalarmultiplication of the current line width. In case of non-grid arrows then you can also have thisas a unit which is recommended as it looks better. If the scalar is < 1 then the overlap is ignored.

overlap_bg_clr

In order to enhance the 3D perspective and to make it easierto follow arrows the arrows have a background color to separate them from those underneath.

type_of_arrow

The types of arrow may be grid, simple, or gradient. Simple gridarrows are thebezierGrob arrows (not that pretty),simple is thebezierArrowSmpl that I've created to get a more exactcontrol of the arrow position and width, while gradientcorresponds tobezierArrowGradientallowing the arrow to have a fill color that slowly turns into the color of the arrow.

abs_arrow_width

The absolute width of the arrow

arrow_clr

The color of the arrows. Usually black, can be a vector indicating each arrowfrom first to last arrow (counting from the top). If the vector is of the same length as theboxes then all box arrows will have the same color (that is all the arrows stemming from theleft boxes)

transition_arrow_props

The proportions of the different transitions ifavailable.

color_bar_subspace

If there is little or no differenceat the low/high proportions of the spectrum then itcan be of interest to focus the color change to the centerleaving the tails constant

plot_arrows

If we are plotting shadow boxes thenarrows should not be plotted and this should be set toFALSE

proportion

It there is a proportion

Value

void


Output boxes

Description

Outputs a list of boxes as produced by either thespread or align functions for boxGrobs.

Usage

## S3 method for class 'Gmisc_list_of_boxes'print(x, ...)

Arguments

x

A list of a set of ['boxGrob']/['boxPropGrob'] to plot

...

Ignored argument


An R alternative to the lodashget in JavaScript

Description

This is a handy function for retrieving items deep in a nested structurewithout causing error if not found

Usage

retrieve(sourceList, path, default = NA)

Arguments

sourceList

Thelist()/c() that is to be searched for the element

path

A string that can be separated by [,] or ., the string"elementname1.1.elementname"is equivalent to"elementname1[[1]]]elementname". Note that the function doesn't checkthe validity of the path - it only separates and tries to address that element with '[[]]'.

default

The value to return if the element isn't found

Value

Returns a sub-element fromsourceList or thedefault value.

See Also

Other lodash similar functions:has()

Examples

source <- list(a = list(b = 1, `odd.name` = 'I hate . in names', c(1,2,3)))retrieve(source, "a.b")retrieve(source, "a.b.1")retrieve(source, "a.odd\\.name")retrieve(source, "a.not_in_list")

Add [Hmisc::label()] to multiple columns

Description

Add label attribute using 'dplyr' syntax using the [Hmisc::label()]

Usage

set_column_labels(x, ...)

Arguments

x

The data frame that we want to label

...

Variable names with their intended label, e.g. 'mpg = "Miles per gallon"'.

Value

The original data.frame

See Also

Other Hmisc helpers:set_column_units()

Examples

library(magrittr)data(mtcars)mtcars_with_labels <- mtcars %>%  set_column_labels(mpg = "Gas",                    cyl = "Cylinders",                    hp = "Strength")Hmisc::label(mtcars_with_labels$mpg)

Add [Hmisc::unit()] to multiple columns

Description

Add label attribute using 'dplyr' syntax using the [Hmisc::unit()]

Usage

set_column_units(x, ...)

Arguments

x

The data frame that we want to define units on

...

Variable names with their intended unit, e.g. 'hp = "Hp"'.

Value

The original data.frame

See Also

Other Hmisc helpers:set_column_labels()

Examples

library(magrittr)data(mtcars)mtcars_with_units <- mtcars %>%  set_column_units(wt = "1000 lbs")Hmisc::units(mtcars_with_units$wt)

Spread boxes

Description

Spreads a set ofboxGrob/boxPropGrob in either horizontal or vertical direction.

Usage

spreadVertical(..., .from = NULL, .to = NULL, .type = c("between", "center"))spreadHorizontal(..., .from = NULL, .to = NULL, .type = c("between", "center"))

Arguments

...

A set of boxes to spread. Can also be alist of boxes.

.from

A box that the spread originates from. If left empty the entireviewport will be used.

.to

A box that the spread ends at. If left empty the entireviewport will be used.

.type

Ifbetween the space between the boxes will be identical whilecenter has each box's center is equally distributed.

Value

list with the boxes that have been spread

See Also

Other flowchart components:align,boxGrob(),boxPropGrob(),connectGrob(),coords(),distance(),moveBox()

Examples

library(grid)grid.newpage()box1 <- boxGrob("B1", x = .2, y = .8)box2 <- boxGrob("B2\n\n\neach\nbox\neven\nspace\nbetween", x = .2, y = .8)box3 <- boxGrob("B3", x = .2, y = .8)box4 <- boxGrob("B4", x = .2, y = .8)box5 <- boxGrob("B5", x = .2, y = .8)spread_boxes <- spreadVertical(box1,                               box2,                               box3,                               a = box4,                               box5,                                .type = "between")for (b in spread_boxes) {  print(b)}box1 <- boxGrob("B1\n\nanother group\ncenter oriented", x = .6, y = .8)box2 <- boxGrob("B2", x = .6, y = .8)box3 <- boxGrob("B3", x = .6, y = .8)box4 <- boxGrob("B4", x = .6, y = .8)box5 <- boxGrob("B5", x = .6, y = .8)spread_boxes <- spreadVertical(box1,                               box2,                               box3,                               a = box4,                               box5,                                .type = "center")for (b in spread_boxes) {  print(b)}

A dense time-span text

Description

When adding a time span text we often don't want to write3 jun - 10 jun butshorten it to3 - 10 jun while retaining month and year info only if the spancrosses between months or years.

Usage

time2spanTxt(  times,  day_month_glue_txt = getOption("Gmisc_time2spanTxt_day_month", default =    "{mday(time)} {month(time, label = TRUE)}"),  full_year_format = getOption("Gmisc_time2spanTxt_full_year", default =    "{mday(time)} {month(time, label = TRUE)} {year(time)}"),  start_stop_glue_txt = getOption("Gmisc_time2spanTxt_template", default =    "{start} to {stop}"))

Arguments

times

The dates or POSIX timestamps to used for time span

day_month_glue_txt

Theglue string to format days and months withtime as the time input

full_year_format

Theglue string to format the full year withtime as the time input

start_stop_glue_txt

The string used in theglue for putting thestart and stop dates together into one string

Details

There are options that can be set using theoptions:

Value

string A string describing the time span

Examples

time2spanTxt(as.POSIXct(c("2020-01-02", "2020-03-01", NA)))# 2 jan to 1 mar

A transition plot

Description

This plot's purpose is to illustrate how states change before andafter. In my research I use it before surgery and after surgerybut it can be used in any situation where you have a change fromone state to another

Usage

transitionPlot(  transition_flow,  type_of_arrow = c("grid", "simple", "gradient"),  box_txt = rownames(transition_flow),  tot_spacing = 0.2,  box_width = 1/4,  fill_start_box = "darkgreen",  txt_start_clr = "white",  fill_end_box = fill_start_box,  txt_end_clr = txt_start_clr,  cex = 2,  min_lwd = if (type_of_arrow == "grid") 1 else unit(0.1, "mm"),  max_lwd = if (type_of_arrow == "grid") 6 else unit(5, "mm"),  lwd_prop_total = TRUE,  arrow_clr = "#000000",  abs_arrow_width = FALSE,  overlap_bg_clr = "#FFFFFF",  overlap_order = 1:nrow(transition_flow),  overlap_add_width = if (type_of_arrow == "grid") 1.5 else unit(1, "mm"),  box_prop,  mar = unit(rep(3, times = 4), "mm"),  main = NULL,  box_label = NULL,  box_label_pos = "top",  box_label_cex = cex,  color_bar = TRUE,  color_bar_cex = cex * 0.33,  color_bar_labels,  color_bar_subspace = NULL,  new_page = FALSE)

Arguments

transition_flow

This should be a matrix with the size of the transitions.The unit for each cell should be number of observations, row/column-proportionswill show incorrect sizes. The matrix needs to be square. The best way to generatethis matrix is probably just do atable(starting_state, end_state). The rowsrepresent the starting positions, while the columns the end positions. I.e. the firstrows third column is the number of observations that go from the first class to thethird class.

type_of_arrow

The types of arrow may be grid, simple, or gradient. Simple gridarrows are thebezierGrob arrows (not that pretty),simple is thebezierArrowSmpl that I've created to get a more exactcontrol of the arrow position and width, while gradientcorresponds tobezierArrowGradientallowing the arrow to have a fill color that slowly turns into the color of the arrow.

box_txt

The text to appear inside of the boxes. If you need line breaksthen you need to manually add a \n inside the string.

tot_spacing

The proportion of the vertical space that is to be leftempty. It is then split evenly between the boxes.

box_width

The width of the box. By default the box is one fourth ofthe plot width.

fill_start_box

The fill color of the start boxes. This can eitherbe a single value or a vector if you desire different colors for eachbox. If you specify box_prop then this has to be a 2 column matrix.

txt_start_clr

The text color of the start boxes. This can eitherbe a single value or a vector if you desire different colors for eachbox. If you specify box_prop then this has to be a 2 column matrix.

fill_end_box

The fill color of the end boxes. This can eitherbe a single value or a vector if you desire different colors for eachbox. If you specify box_prop then this has to be a 2 column matrix.

txt_end_clr

The text color of the end boxes. This can eitherbe a single value or a vector if you desire different colors for eachbox. If you specify box_prop then this has to be a 2 column matrix.

cex

The cexgpar of the text

min_lwd

The minimum width of the line that we want to illustrate thetranisition with.

max_lwd

The maximum width of the line that we want to illustrate thetranisition with.

lwd_prop_total

The width of the lines may be proportional to either theother flows from that box, or they may be related to all flows. This is a booleanparameter that is set to true by default, i.e. relating to all flows.

arrow_clr

The color of the arrows. Usually black, can be a vector indicating each arrowfrom first to last arrow (counting from the top). If the vector is of the same length as theboxes then all box arrows will have the same color (that is all the arrows stemming from theleft boxes)

abs_arrow_width

The width can either be absolute, i.e. each arrow headed for a boxhas the exact same width. The alternative is that the width is related to the line width.

overlap_bg_clr

In order to enhance the 3D perspective and to make it easierto follow arrows the arrows have a background color to separate them from those underneath.

overlap_order

The order from first->last for the lines. This means that the lastline will be on top while the first one will appear at the bottom. This should be providedas a vector.

overlap_add_width

The width of the white cross-over line. You can specify this as a scalarmultiplication of the current line width. In case of non-grid arrows then you can also have thisas a unit which is recommended as it looks better. If the scalar is < 1 then the overlap is ignored.

box_prop

If you want the boxes to have proportions indicating some other factors then inputa matrix with quantiles for the proportions. Note the size must benrow(transition_flow) x 2.

mar

A numerical vector of the form c(bottom, left, top, right) of the typeunit()

main

The title of the plot if any, defaultNULL

box_label

A vector of length 2 if you want to label each box column

box_label_pos

The position of the label, either'top' or'bottom'

box_label_cex

The cex of the label, defaults to the default cex

color_bar

If you have proportions inside the transition_flow variablethen the color_bar will automatically appear at the bottom unless you setthis toFALSE

color_bar_cex

The size of the tick labels for the color bar

color_bar_labels

The labels of the two proportions that make up the color bar.Defaults to the labels of the third dimension for thetransition_flowargument.

color_bar_subspace

If there is little or no differenceat the low/high proportions of the spectrum then itcan be of interest to focus the color change to the centerleaving the tails constant

new_page

If you want the plot to appear on a new blank page then set this toTRUE, bydefault it isFALSE.

Value

void

Examples

# This example does not run since it# takes a little while to assemble the# arrows and RMD Check complains that this# is more than allowed forlibrary(grid)par_org <- par(ask = TRUE)# Settingsno_boxes <- 3# Generate test settingtransition_matrix <- matrix(NA, nrow = no_boxes, ncol = no_boxes)transition_matrix[1, ] <- 200 * c(.5, .25, .25)transition_matrix[2, ] <- 540 * c(.75, .10, .15)transition_matrix[3, ] <- 340 * c(0, .2, .80)grid.newpage()transitionPlot(transition_matrix,  box_txt = c("First", "Second", "Third"),  type_of_arrow = "simple",  min_lwd = unit(1, "mm"),  max_lwd = unit(6, "mm"),  overlap_add_width = unit(1, "mm"))# Setup proportionsbox_prop <- cbind(c(1, 0, 0.5), c(.52, .2, .8))# From the Set2 Colorbrewerstart_box_clr <- c("#8DA0CB", "#FC8D62")# Darken the colors slightlyend_box_clr <- c(  colorRampPalette(c(start_box_clr[1], "#000000"))(10)[2],  colorRampPalette(c(start_box_clr[2], "#000000"))(10)[2])# Create a new gridgrid.newpage()transitionPlot(transition_matrix,  box_prop = box_prop,  fill_start_box = start_box_clr, fill_end_box = end_box_clr,  txt_start_clr = c("#FFFFFF", "#000000"), txt_end_clr = c("#FFFFFF", "#000000"),  box_txt = c("First", "Second", "Third"),  type_of_arrow = "gradient",  min_lwd = unit(1, "mm"),  max_lwd = unit(10, "mm"),  overlap_add_width = unit(1, "mm"))par(par_org)

Checks the input of a vector

Description

It checks that a vector makes sense in itsgrid parameters. It also creates an origoat point 0 if none is provided.

Usage

validateAndConvertVectorInputs(x, y, x_origo, y_origo)

Arguments

x

The x point of the vector

y

The y point of the vector

x_origo

The x origin if other than 0

y_origo

The y origin if other than 0

Value

list with the input variables checked andconverted if necessary.


Outputs an object

Description

Manually viewing a list object can be tricky where the natural printcan be hard to work through. The config format *yaml* is increadiblydense and useful not only for writing configs but also viewing themwhich 'yamlDump' helps with.

Usage

yamlDump(x)

Arguments

x

An object thatas.yaml accepts

Value

void

Examples

some_fancy_list <- list(complex = list(some_data = 1:3,                                       other_data = list(name = "Max")),                        simple = "awesome overview")yamlDump(some_fancy_list)#complex:#  some_data:#  - 1#  - 2#  - 3#  other_data:#    name: Max#simple: awesome overview# If you got a character json you can also input it directly# and the function will automatically convert it to a listyamlDump('{"a":{"b":["1"]}}')

[8]ページ先頭

©2009-2025 Movatter.jp