# Attach packages
library(rearrr)
library(dplyr)
library(purrr)
has_ggplot <- require(ggplot2) # Attach if installed
# Set seed
set.seed(1)
# Create a data frame
df <- data.frame(
"y" = runif(200),
"g" = factor(rep(1:5, each = 40))
)
# Triangularize 'y'
df_tri <- triangularize(df, y_col = "y")
df_tri
# Plot triangle
if (has_ggplot){
df_tri %>%
ggplot(aes(x = .triangle_x, y = y, color = .edge)) +
geom_point() +
theme_minimal()
}
#
# Grouped squaring
#
# Triangularize 'y' for each group
# First cluster the groups a bit to move the
# triangles away from each other
df_tri <- df %>%
cluster_groups(
cols = "y",
group_cols = "g",
suffix = "",
overwrite = TRUE
) %>%
dplyr::group_by(g) %>%
triangularize(
y_col = "y",
overwrite = TRUE
)
# Plot triangles
if (has_ggplot){
df_tri %>%
ggplot(aes(x = .triangle_x, y = y, color = g)) +
geom_point() +
theme_minimal()
}
#
# Specifying minimum value
#
# Specify minimum value manually
df_tri <- triangularize(df, y_col = "y", .min = -2)
df_tri
# Plot triangle
if (has_ggplot){
df_tri %>%
ggplot(aes(x = .triangle_x, y = y, color = .edge)) +
geom_point() +
theme_minimal()
}
#
# Multiple triangles by contraction
#
# \donttest{
# Start by squaring 'y'
df_tri <- triangularize(df, y_col = "y")
# Contract '.triangle_x' and 'y' towards the centroid
# To contract with multiple multipliers at once,
# we wrap the call in purrr::map_dfr
df_expanded <- purrr::map_dfr(
.x = 1:10 / 10,
.f = function(mult) {
expand_distances(
data = df_tri,
cols = c(".triangle_x", "y"),
multiplier = mult,
origin_fn = centroid,
overwrite = TRUE
)
}
)
df_expanded
if (has_ggplot){
df_expanded %>%
ggplot(aes(
x = .triangle_x_expanded, y = y_expanded,
color = .edge, alpha = .multiplier
)) +
geom_point() +
theme_minimal()
}
# }
Run the code above in your browser using DataLab