Title: | Miscellaneous functions from W. Joel Schneider |
---|---|
Description: | Several functions I find useful. |
Authors: | W. Joel Schneider [aut, cre] |
Maintainer: | W. Joel Schneider <[email protected]> |
License: | CC0 |
Version: | 0.3 |
Built: | 2024-11-08 05:44:44 UTC |
Source: | https://github.com/wjschne/WJSmisc |
Convert angles to ggplot2 hjust
angle2hjust(theta, multiplier = 1.5, as_degrees = FALSE)
angle2hjust(theta, multiplier = 1.5, as_degrees = FALSE)
theta |
angle in radians |
multiplier |
distance from point |
as_degrees |
use degrees instead of radians |
numeric
Convert angles to ggplot2 vjust
angle2vjust(theta, multiplier = 1.5, as_degrees = FALSE)
angle2vjust(theta, multiplier = 1.5, as_degrees = FALSE)
theta |
angle in radians |
multiplier |
distance from point |
as_degrees |
use degrees instead of radians |
numeric
library(tibble) library(ggplot2) library(dplyr) xy_ratio <- pi tibble(theta = seq(0,2*pi, length.out = 9), y = sin(theta), slope = cos(theta) * xy_ratio, text_angle = atan(slope) + pi / 2) %>% ggplot(aes(theta,y)) + stat_function(fun = sin) + geom_point() + geom_label(aes(label = LETTERS[1:9], vjust = angle2vjust(text_angle, multiplier = 1.5), hjust = angle2hjust(text_angle, multiplier = 1.5)), label.size = NA, label.padding = unit(1, "mm")) + scale_x_continuous(expression(theta), breaks = seq(0,2*pi, length.out = 9), labels = label_parsed(c("0", "frac(pi,4)", "frac(pi,2)", "frac(3 * pi,4)", "pi", "frac(5*pi,4)", "frac(3 * pi,2)", "frac(7*pi,4)", "2*pi"))) + scale_y_continuous(expression(sin(theta))) + coord_fixed(ratio = xy_ratio, clip = "off") + theme_minimal()
library(tibble) library(ggplot2) library(dplyr) xy_ratio <- pi tibble(theta = seq(0,2*pi, length.out = 9), y = sin(theta), slope = cos(theta) * xy_ratio, text_angle = atan(slope) + pi / 2) %>% ggplot(aes(theta,y)) + stat_function(fun = sin) + geom_point() + geom_label(aes(label = LETTERS[1:9], vjust = angle2vjust(text_angle, multiplier = 1.5), hjust = angle2hjust(text_angle, multiplier = 1.5)), label.size = NA, label.padding = unit(1, "mm")) + scale_x_continuous(expression(theta), breaks = seq(0,2*pi, length.out = 9), labels = label_parsed(c("0", "frac(pi,4)", "frac(pi,2)", "frac(3 * pi,4)", "pi", "frac(5*pi,4)", "frac(3 * pi,2)", "frac(7*pi,4)", "2*pi"))) + scale_y_continuous(expression(sin(theta))) + coord_fixed(ratio = xy_ratio, clip = "off") + theme_minimal()
Converts the default values of a function's arguments to variables and attaches them to the global environment
attach_function(f)
attach_function(f)
f |
Function |
Attaches function arguments to global environment
my_function <- function(x, y = 2) x + y # Sets y to 2 attach_function(my_function)
my_function <- function(x, y = 2) x + y # Sets y to 2 attach_function(my_function)
Generate correlation ellipse data
cor_ellipse( r = 0, mean = c(0, 0), sd = c(1, 1), p = 0.95, split_x = NULL, split_y = NULL, n_points = 10000 )
cor_ellipse( r = 0, mean = c(0, 0), sd = c(1, 1), p = 0.95, split_x = NULL, split_y = NULL, n_points = 10000 )
r |
Correlation coefficient |
mean |
Vector of 2 means |
sd |
Vector of 2 standard deviations |
p |
Proportion of data ellipse covers |
split_x |
Split ellipse at x value |
split_y |
Split ellipse at y value |
n_points |
Number of points |
data.frame
cor_ellipse(r = .75)
cor_ellipse(r = .75)
Correlation plot
cor_heat( d, test_names = colnames(d), margins = 0.55, text_size = 4, dendrograms = TRUE, palette_col = c("firebrick", "white", "royalblue"), x_label_angle = 90, reorder_vars = TRUE, heat.lim = c(-1, 1), heat.pal.values = seq(0, 1, 1/(length(palette_col) - 1)), ... )
cor_heat( d, test_names = colnames(d), margins = 0.55, text_size = 4, dendrograms = TRUE, palette_col = c("firebrick", "white", "royalblue"), x_label_angle = 90, reorder_vars = TRUE, heat.lim = c(-1, 1), heat.pal.values = seq(0, 1, 1/(length(palette_col) - 1)), ... )
d |
Data or correlation matrix |
test_names |
Vector of names of variables |
margins |
Width of margins for labels |
text_size |
Size of text |
dendrograms |
If TRUE, add dendrograms |
palette_col |
A vector of three colors for heatmap |
x_label_angle |
Angle of x-axis label |
reorder_vars |
If TRUE, reorder variables based on cluster analysis |
heat.lim |
Vector of the lower and upper bounds on heat map |
heat.pal.values |
Vector of values of where on the scale each color in palette_col falls. Defaults to even spacing. |
... |
Additional parameters passed to superheat::superheat |
Format text of a correlation matrix
cor_text(r, digits = 2, remove_leading_zero = TRUE, remove_diagonal = FALSE)
cor_text(r, digits = 2, remove_leading_zero = TRUE, remove_diagonal = FALSE)
r |
a matrix of correlations |
digits |
Number of digits to round |
remove_leading_zero |
If TRUE, remove leading zero from all correlations |
remove_diagonal |
If TRUE, remove diagonal of ones |
a matrix of correlations as text
cor_text(matrix(.5,2,2))
cor_text(matrix(.5,2,2))
Converts a correlation matrix to a partial correlation matrix
cor2pcor(R)
cor2pcor(R)
R |
correlation matrix |
Partial correlation matrix
R <- matrix(.6, nrow = 3, ncol = 3) diag(R) <- 1 cor2pcor(R)
R <- matrix(.6, nrow = 3, ncol = 3) diag(R) <- 1 cor2pcor(R)
Name for square arrays like correlation matrices
cornames(x) <- value
cornames(x) <- value
x |
a square array, matrix, or data.frame |
value |
a vector of names |
a named square array, matrix, or data.frame
R <- tri2cor(.5) cornames(R) <- c("A", "B")
R <- tri2cor(.5) cornames(R) <- c("A", "B")
Create unique combinations of vectors
cross_vectors(..., sep = "_")
cross_vectors(..., sep = "_")
... |
vectors |
sep |
Separate character |
A character vector
cross_vectors(c("a", "b"), c(1,2))
cross_vectors(c("a", "b"), c(1,2))
Convert data.frame and tibbles to matrices with named rows and columns
df2matrix(d, first_col_is_row_names = TRUE)
df2matrix(d, first_col_is_row_names = TRUE)
d |
data.frame or tibble |
first_col_is_row_names |
TRUE if first column has row names |
matrix
d <- data.frame(rname = c("x1", "x2"), x1 = c(1,2), x2 = c(3,4)) df2matrix(d)
d <- data.frame(rname = c("x1", "x2"), x1 = c(1,2), x2 = c(3,4)) df2matrix(d)
A wrapper for ggtext::geom_richtext
geom_richlabel( mapping, label.margin = unit(2, "mm"), label.padding = unit(0.5, "mm"), label.color = NA, fill = "white", text_size = 12, ... )
geom_richlabel( mapping, label.margin = unit(2, "mm"), label.padding = unit(0.5, "mm"), label.color = NA, fill = "white", text_size = 12, ... )
mapping |
aes() |
label.margin |
grid unit margin |
label.padding |
grid unit margin |
label.color |
color |
fill |
color |
text_size |
text size in point units |
... |
additional parameters passed to ggtext::geom_richtext |
ggtext::geom_richtext
library(tibble) library(ggplot2) library(dplyr) library(WJSmisc) tibble(x = 0, y = 0, l = "A") %>% ggplot() + geom_richlabel(aes(x,y,label = l))
library(tibble) library(ggplot2) library(dplyr) library(WJSmisc) tibble(x = 0, y = 0, l = "A") %>% ggplot() + geom_richlabel(aes(x,y,label = l))
Retrieve text within a span or div with a named id
get_quote(id, file, blockquote = TRUE)
get_quote(id, file, blockquote = TRUE)
id |
the id string (without #). |
file |
file name |
blockquote |
return as block quote (defaults to TRUE) |
a character vector of length 1
Save ggplot as .pdf, then convert to .svg via pdf2svg
ggsvg(f, width = 6.5, height = 6.5, ...)
ggsvg(f, width = 6.5, height = 6.5, ...)
f |
Filename of the svg file. Omit the ".svg" at the end. |
width |
width passed to ggplot2::ggsave |
height |
width passed to ggplot2::ggsave |
... |
Additional parameters passed to ggplot2::ggsave |
Convert ggplot theme font size to geom_text size
ggtext_size(base_size, ratio = 0.8)
ggtext_size(base_size, ratio = 0.8)
base_size |
theme font size |
ratio |
ratio of text size to theme font size. Defaults to .8 so that geom text will be the same size as default sized axis labels. |
numeric vector
ggtext_size(16)
ggtext_size(16)
Insert latex colors into a matrix
insert_latex_color( m, color_cells, color_rownames = NULL, color_colnames = NULL )
insert_latex_color( m, color_cells, color_rownames = NULL, color_colnames = NULL )
m |
matrix of values |
color_cells |
matrix of latex colors for matrix cells |
color_rownames |
vector of latex colors for row names |
color_colnames |
vector of latex colors for column names |
matrix
# A matrix of zeros m <- matrix(0, nrow = 2, ncol = 2) # A matrix of NA values the same size as m latex_colors <- m * NA # Make the top row red latex_colors[1,] <- "red" # Insert colors into m insert_latex_color(m, latex_colors)
# A matrix of zeros m <- matrix(0, nrow = 2, ncol = 2) # A matrix of NA values the same size as m latex_colors <- m * NA # Make the top row red latex_colors[1,] <- "red" # Insert colors into m insert_latex_color(m, latex_colors)
Make latex array
latexarray( M, left = "", right = "", env = "array", includenames = TRUE, align = NULL, lines = TRUE )
latexarray( M, left = "", right = "", env = "array", includenames = TRUE, align = NULL, lines = TRUE )
M |
A matrix |
left |
left delimiter options: [(| |
right |
right delimiter options: ])| |
env |
Array environment |
includenames |
Include column and row names |
align |
Column alignment. For a three column matrix, alignment defaults to centering columns("ccc"). If there are row labels, the default would be "r|ccc" to right-align the row labels and separate them with vertical line. |
lines |
Include lines separating column and row names |
character string
M <- diag(3) colnames(M) <- LETTERS[1:3] rownames(M) <- LETTERS[1:3] latexarray(M)
M <- diag(3) colnames(M) <- LETTERS[1:3] rownames(M) <- LETTERS[1:3] latexarray(M)
Regression from correlation matrix
lm_matrix(R, ind, dep)
lm_matrix(R, ind, dep)
R |
correlation matrix |
ind |
independent variables |
dep |
dependent variable |
list of coefficients and R2
Make latent variable indicators with rbeta_ms function
make_indicators( latent, indicators = NULL, mu = 0.8, sigma = 0.05, k = 3, digits = 3 )
make_indicators( latent, indicators = NULL, mu = 0.8, sigma = 0.05, k = 3, digits = 3 )
latent |
name of latent variable |
indicators |
vector of indicator names (assigned automatically if left NULL) |
mu |
mean of standardized coefficients |
sigma |
sd of standardized coeficients |
k |
number of indicator variables |
digits |
number of digits to round coefficients |
lavaan code for latent variable assignment
make_indicators("depression", mu = 0.8, sigma = 0.05, k = 4)
make_indicators("depression", mu = 0.8, sigma = 0.05, k = 4)
generates simple slopes plot from moderated regression equation
modregplot( predictor_range = c(-4, 4), moderator_values = c(-1, 0, 1), intercept = 0, predictor_coef = 0, moderator_coef = 0, interaction_coef = 0, predictor_label = "X", criterion_label = "Y", moderator_label = "Moderator" )
modregplot( predictor_range = c(-4, 4), moderator_values = c(-1, 0, 1), intercept = 0, predictor_coef = 0, moderator_coef = 0, interaction_coef = 0, predictor_label = "X", criterion_label = "Y", moderator_label = "Moderator" )
predictor_range |
a length 2 vector of the range of values to be plotted on the predictor variable, Default: c(-4, 4) |
moderator_values |
a vector of moderator values to be plotted, Default: c(-1, 0, 1) |
intercept |
the intercept of the regression equation, Default: 0 |
predictor_coef |
the regression coefficient for the predictor variable, Default: 0 |
moderator_coef |
the regression coefficient for the moderator variable, Default: 0 |
interaction_coef |
the interaction term coefficent, Default: 0 |
predictor_label |
the label for the predictor variable, Default: 'X' |
criterion_label |
the label for the moderator variable, Default: 'Y' |
moderator_label |
PARAM_DESCRIPTION, Default: 'Moderator' |
a ggplot of the simple slopes
modregplot( predictor_range = c(-2, 2), moderator_values = c(Low = -1, High = 1), intercept = 6, predictor_coef = 2, moderator_coef = 0, interaction_coef = 1, predictor_label = "Psychopathy", criterion_label = "Aggression", moderator_label = "Impulsivity" )
modregplot( predictor_range = c(-2, 2), moderator_values = c(Low = -1, High = 1), intercept = 6, predictor_coef = 2, moderator_coef = 0, interaction_coef = 1, predictor_label = "Psychopathy", criterion_label = "Aggression", moderator_label = "Impulsivity" )
General a multivariate confidence interval for a set of scores
multivariate_ci(x, rxx, mu, sigma, ci = 0.95, v_names = names(x))
multivariate_ci(x, rxx, mu, sigma, ci = 0.95, v_names = names(x))
x |
a vector of scores |
rxx |
a vector reliability coefficients |
mu |
a vector means |
sigma |
a covariance matrix |
ci |
confidence level |
v_names |
a vector of names |
data.frame
x_wisc <- c( vci = 130, vsi = 130, fri = 70, wmi = 130, psi = 130 ) rxx_wisc <- c( vci = .92, vsi = .92, fri = .93, wmi = .92, psi = .88 ) R_wisc <- (" index vci vsi fri wmi psi vci 1.00 0.59 0.59 0.53 0.30 vsi 0.59 1.00 0.62 0.50 0.36 fri 0.59 0.62 1.00 0.53 0.31 wmi 0.53 0.50 0.53 1.00 0.36 psi 0.30 0.36 0.31 0.36 1.00") |> readr::read_tsv() |> tibble::column_to_rownames("index") |> as.matrix() multivariate_ci( x = x_wisc, rxx = rxx_wisc, mu = rep(100, 5), sigma = R_wisc * 225 )
x_wisc <- c( vci = 130, vsi = 130, fri = 70, wmi = 130, psi = 130 ) rxx_wisc <- c( vci = .92, vsi = .92, fri = .93, wmi = .92, psi = .88 ) R_wisc <- (" index vci vsi fri wmi psi vci 1.00 0.59 0.59 0.53 0.30 vsi 0.59 1.00 0.62 0.50 0.36 fri 0.59 0.62 1.00 0.53 0.31 wmi 0.53 0.50 0.53 1.00 0.36 psi 0.30 0.36 0.31 0.36 1.00") |> readr::read_tsv() |> tibble::column_to_rownames("index") |> as.matrix() multivariate_ci( x = x_wisc, rxx = rxx_wisc, mu = rep(100, 5), sigma = R_wisc * 225 )
ggplot of parallel analysis from the psych package
parallel_analysis( d, fm = "pa", factor_based = TRUE, vcolors = c("firebrick", "royalblue"), font_family = "sans", ... )
parallel_analysis( d, fm = "pa", factor_based = TRUE, vcolors = c("firebrick", "royalblue"), font_family = "sans", ... )
d |
data to be analyzed |
fm |
factor method passed to psych::fa.parallel |
factor_based |
TRUE is factor-based and FALSE is principal component-based |
vcolors |
vector of 2 colors for lines |
font_family |
Name of font |
... |
parameters passed to psych::fa.parallel |
d <- psych::bfi[,1:25] parallel_analysis(d)
d <- psych::bfi[,1:25] parallel_analysis(d)
Paste matrix code from clipboard
paste_matrix_from_clipboard(digits = 2, as_matrix = TRUE)
paste_matrix_from_clipboard(digits = 2, as_matrix = TRUE)
digits |
Number of digits to round |
as_matrix |
Convert to matrix. Defaults to 'TRUE' |
Function that converts pdf files to svg. Must have the pdf2svg program installed (https://github.com/dawbarton/pdf2svg)
pdf2svg(f)
pdf2svg(f)
f |
Filename of the pdf file. Omit the ".pdf" at the end. |
Creats a plot of factor loadings
plot_loading( f, font_family = "sans", font_size = 14, loading_text_size = font_size * 0.8, factor_names = sort(colnames(f$loadings)), nudge_loadings = 0.05 )
plot_loading( f, font_family = "sans", font_size = 14, loading_text_size = font_size * 0.8, factor_names = sort(colnames(f$loadings)), nudge_loadings = 0.05 )
f |
output of a factor analysis from the psych::fa function |
font_family |
Name of font |
font_size |
Size of font |
loading_text_size |
size of loading font, |
factor_names |
names of the factors #' |
nudge_loadings |
nudge loadings on x dimension |
library(GPArotation) library(psych) fit <- fa(psych::bfi[,1:25], nfactors = 5) plot_loading(fit)
library(GPArotation) library(psych) fit <- fa(psych::bfi[,1:25], nfactors = 5) plot_loading(fit)
Plot a normal distribution shading below x
plotnorm( x = 0, mu = 0, sigma = 1, below = TRUE, show_proportion = TRUE, show_x = TRUE, show_param = TRUE, text_size = 14, font_family = "sans", shade_fill = "royalblue" )
plotnorm( x = 0, mu = 0, sigma = 1, below = TRUE, show_proportion = TRUE, show_x = TRUE, show_param = TRUE, text_size = 14, font_family = "sans", shade_fill = "royalblue" )
x |
number to divide normal distribution |
mu |
mean of normal distribution |
sigma |
standard deviation of normal distribution |
below |
If TRUE, shade lower portion of normal distribution |
show_proportion |
If TRUE, display proportions |
show_x |
If TRUE, display x value |
show_param |
If TRUE, display mean and standard deviation |
text_size |
Base text size |
font_family |
Name of font |
shade_fill |
Color of shaded region |
plotnorm(90, 100, 15)
plotnorm(90, 100, 15)
Format numeric probabilities as text labels
prob_label( p, accuracy = 0.01, digits = NULL, max_digits = NULL, remove_leading_zero = TRUE, round_zero_one = TRUE )
prob_label( p, accuracy = 0.01, digits = NULL, max_digits = NULL, remove_leading_zero = TRUE, round_zero_one = TRUE )
p |
numeric vector of probabilities |
accuracy |
accuracy of rounding |
digits |
Optional. Number of digits to round. Overrides accuracy parameter |
max_digits |
Optional. Maximum zeros or nines before rounding to 0 or 1 |
remove_leading_zero |
Removes leading zero from probability |
round_zero_one |
Apply rounding to 0 and 1 |
character vector
prob_label(seq(0,1, 0.1))
prob_label(seq(0,1, 0.1))
Rounds proportions to significant digits both near 0 and 1
proportion_round(p, digits = 2)
proportion_round(p, digits = 2)
p |
probabiity |
digits |
rounding digits |
numeric vector
proportion_round(0.01111)
proportion_round(0.01111)
Rounds proportions to significant digits both near 0 and 1, then converts to percentiles
proportion2percentile( p, digits = 2, remove_leading_zero = TRUE, add_percent_character = FALSE )
proportion2percentile( p, digits = 2, remove_leading_zero = TRUE, add_percent_character = FALSE )
p |
probability |
digits |
rounding digits |
remove_leading_zero |
If TRUE, remove leading zero |
add_percent_character |
If TRUE, add percent character |
character vector
proportion2percentile(0.011111)
proportion2percentile(0.011111)
Probability a true score will be below a threshold
pthreshold(x, threshold, rxx, mu = 0, sigma = 1)
pthreshold(x, threshold, rxx, mu = 0, sigma = 1)
x |
observed score |
threshold |
threshold |
rxx |
reliability coefficient |
mu |
population mean |
sigma |
population standard deviation |
probability
pthreshold(x = .5, threshold = 1, rxx = 0.9)
pthreshold(x = .5, threshold = 1, rxx = 0.9)
APA p-value rounding
pvalueAPA(p, inline = FALSE, mindigits = 2, maxdigits = 3)
pvalueAPA(p, inline = FALSE, mindigits = 2, maxdigits = 3)
p |
probabiity |
inline |
to be used in an inline rmarkdown (default is FALSE) |
mindigits |
minimum rounding digits |
maxdigits |
maximum rounding digits |
character
pvalueAPA(0.01111)
pvalueAPA(0.01111)
Random beta distribution with specified mean and sd
rbeta_ms(n = 1, mu = 0.5, sigma = 0.025)
rbeta_ms(n = 1, mu = 0.5, sigma = 0.025)
n |
Number of data points |
mu |
Mean of random beta distribution |
sigma |
SD of random beta distribution |
a vector of numeric values
rbeta_ms(n = 5, mu = 0.8, sigma = 0.1)
rbeta_ms(n = 5, mu = 0.8, sigma = 0.1)
Remove leading zero from numbers
remove_leading_zero(x, digits = 2, ...)
remove_leading_zero(x, digits = 2, ...)
x |
vector of numbers |
digits |
rounding digits |
... |
Arguments passed to formatC |
vector of characters
remove_leading_zero(c(0.5,-0.2))
remove_leading_zero(c(0.5,-0.2))
Rotate a 2-column matrix
rotate2dmatrix(x, theta, degrees = FALSE, origin = c(0, 0))
rotate2dmatrix(x, theta, degrees = FALSE, origin = c(0, 0))
x |
a 2-column matrix |
theta |
angle |
degrees |
if TRUE, theta is in degrees instead of radians |
origin |
point of rotation |
a rotated 2-column matrix
x <- matrix(seq(10), ncol = 2) rotate2dmatrix(x, pi)
x <- matrix(seq(10), ncol = 2) rotate2dmatrix(x, pi)
A wrapper function for the signs::signs function. It adds a figure space to negative numbers so that it appear as if the minus sign does not affect the number's centering.
signs_centered(x, space = " ", ...)
signs_centered(x, space = " ", ...)
x |
a numeric vector |
space |
a character to be added to negative numbers (defaults to a figure space) |
... |
parameters passed to signs:signs |
a vector of numbers converted to characters
library(ggplot2) d <- data.frame(x = -4:0, y = -4:0) # In these 2 plots, Compare the centering of the negative numbers on the x-axis ggplot(d, aes(x,y)) ggplot(d, aes(x,y)) + scale_x_continuous(labels = signs_centered)
library(ggplot2) d <- data.frame(x = -4:0, y = -4:0) # In these 2 plots, Compare the centering of the negative numbers on the x-axis ggplot(d, aes(x,y)) ggplot(d, aes(x,y)) + scale_x_continuous(labels = signs_centered)
Draw skewed axes in ggplot2
skewed_axis( theta, axis_title = "X", draw_ticks = TRUE, draw_axis_text = TRUE, remove_origin = TRUE, tick_height = 0.02, lwd = 0.5, text_size = 12, color = NA, family = NA, mu = 0, sigma = 1, tick_label_interval = ifelse(sigma%%3 == 0, 3, 2) )
skewed_axis( theta, axis_title = "X", draw_ticks = TRUE, draw_axis_text = TRUE, remove_origin = TRUE, tick_height = 0.02, lwd = 0.5, text_size = 12, color = NA, family = NA, mu = 0, sigma = 1, tick_label_interval = ifelse(sigma%%3 == 0, 3, 2) )
theta |
angle in radians |
axis_title |
character |
draw_ticks |
logical |
draw_axis_text |
logical |
remove_origin |
logical |
tick_height |
height of ticks |
lwd |
line width |
text_size |
size of text |
color |
color of lines |
family |
font family |
mu |
mean of variable |
sigma |
standard deviation of variable |
tick_label_interval |
interval of ticks |
plot
library(ggplot2) ggplot(data.frame(x = c(0,1), y = c(4,4))) + skewed_axis(pi / 2, color = "black") + skewed_axis(pi / 4, color = "black") + skewed_axis(0, color = "black") + theme_void() + coord_equal()
library(ggplot2) ggplot(data.frame(x = c(0,1), y = c(4,4))) + skewed_axis(pi / 2, color = "black") + skewed_axis(pi / 4, color = "black") + skewed_axis(0, color = "black") + theme_void() + coord_equal()
Convert snake case to subscript
snake2subscript( x, sep = "_", prefix = "<sub>", suffix = "</sub>", collapse = NULL, recycle0 = FALSE )
snake2subscript( x, sep = "_", prefix = "<sub>", suffix = "</sub>", collapse = NULL, recycle0 = FALSE )
x |
character |
sep |
separator defaults to "_" |
prefix |
character prefix |
suffix |
character suffix |
collapse |
character parameter passed to paste0 |
recycle0 |
parameter passed to paste0 |
a character
snake2subscript("x_1")
snake2subscript("x_1")
Wrap sentence strings into lines of roughly equal width
str_wrap_equal(x, max_width = 30L, sep = "\n")
str_wrap_equal(x, max_width = 30L, sep = "\n")
x |
a character vector |
max_width |
the maximum number of characters in a line (unless a word is longer than 'max_width') |
sep |
character string that separates text lines |
a character vector
library(ggplot2) library(stringr) library(dplyr) d <- data.frame( Item = c( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "Duis pretium arcu quis nibh elementum, sed aliquam enim dignissim.", "Nullam et ornare enim, et egestas odio.", "Aliquam posuere ante quis magna rutrum, id elementum nulla sodales.", "Interdum et malesuada fames ac ante ipsum primis in faucibus.", "Aenean rutrum lorem at metus pretium, malesuada porta tellus facilisis.", "Vestibulum at convallis enim.", "Nam malesuada bibendum rutrum.", "Donec risus sapien, pulvinar vitae porttitor non, lobortis ac felis." ), Proportion = seq(.1,.9,.1) ) |> mutate(Item = forcats::fct_inorder(Item)) # Axis labels with stringr::str_wrap ggplot(d, aes(Proportion, Item)) + geom_col() + scale_y_discrete(NULL, labels = \(x) str_wrap(x, width = 25L)) # Axis labels with WJSmisc::str_wrap_equal ggplot(d, aes(Proportion, Item)) + geom_col() + scale_y_discrete(NULL, labels = \(x) str_wrap_equal(x, max_width = 25L))
library(ggplot2) library(stringr) library(dplyr) d <- data.frame( Item = c( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "Duis pretium arcu quis nibh elementum, sed aliquam enim dignissim.", "Nullam et ornare enim, et egestas odio.", "Aliquam posuere ante quis magna rutrum, id elementum nulla sodales.", "Interdum et malesuada fames ac ante ipsum primis in faucibus.", "Aenean rutrum lorem at metus pretium, malesuada porta tellus facilisis.", "Vestibulum at convallis enim.", "Nam malesuada bibendum rutrum.", "Donec risus sapien, pulvinar vitae porttitor non, lobortis ac felis." ), Proportion = seq(.1,.9,.1) ) |> mutate(Item = forcats::fct_inorder(Item)) # Axis labels with stringr::str_wrap ggplot(d, aes(Proportion, Item)) + geom_col() + scale_y_discrete(NULL, labels = \(x) str_wrap(x, width = 25L)) # Axis labels with WJSmisc::str_wrap_equal ggplot(d, aes(Proportion, Item)) + geom_col() + scale_y_discrete(NULL, labels = \(x) str_wrap_equal(x, max_width = 25L))
Create square correlation matrix from lower triangle
tri2cor(x, variable_names = NULL)
tri2cor(x, variable_names = NULL)
x |
vector of correlations |
variable_names |
a vector of variable names |
square matrix
tri2cor(c(.2,.3,.4))
tri2cor(c(.2,.3,.4))
Compute the angle of a vector
vector_angle(x, origin = c(0, 0), degrees = FALSE, allow_negative = FALSE)
vector_angle(x, origin = c(0, 0), degrees = FALSE, allow_negative = FALSE)
x |
A length-2 vector |
origin |
A length-2 vector |
degrees |
If TRUE, returns angles in degrees instead of radians |
allow_negative |
If TRUE, returns angles between -pi and pi (-180 and +180. If FALSE, returns angles between 0 and 2 * pi (0 and 360) |
A length-1 vector
vector_angle(c(1,1)) vector_angle(c(1,1), degrees = TRUE)
vector_angle(c(1,1)) vector_angle(c(1,1), degrees = TRUE)
Convert x to a z-score
x2z(x, mu = mean(x, na.rm = T), sigma = stats::sd(x, na.rm = T))
x2z(x, mu = mean(x, na.rm = T), sigma = stats::sd(x, na.rm = T))
x |
a numeric vector |
mu |
mean |
sigma |
standard deviation |