# Attach packages
library(rearrr)
library(dplyr)
has_ggplot <- require(ggplot2) # Attach if installed
# Set seed
set.seed(3)
# Create a data frame
df <- data.frame(
"x" = 1:12,
"y" = 13:24,
"z" = runif(12),
"g" = c(
1, 1, 1, 1, 2, 2,
2, 2, 3, 3, 3, 3
)
)
# Apply identity matrix
mat <- matrix(c(1, 0, 0, 0, 1, 0, 0, 0, 1), nrow = 3)
apply_transformation_matrix(
data = df,
mat = mat,
cols = c("x", "y", "z"),
origin = c(0, 0, 0)
)
# Apply rotation matrix
# 90 degrees around z-axis
# Origin is the most centered point
mat <- matrix(c(0, 1, 0, -1, 0, 0, 0, 0, 1), nrow = 3)
res <- apply_transformation_matrix(
data = df,
mat = mat,
cols = c("x", "y", "z"),
origin_fn = most_centered
)
# Plot the rotation
# z wasn't changed so we plot x and y
if (has_ggplot){
res %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
geom_point(aes(x = x_transformed, y = y_transformed)) +
theme_minimal()
}
# Apply rotation matrix to grouped data frame
# Around centroids
# Same matrix as before
res <- apply_transformation_matrix(
data = dplyr::group_by(df, g),
mat = mat,
cols = c("x", "y", "z"),
origin_fn = centroid
)
# Plot the rotation
if (has_ggplot){
res %>%
ggplot(aes(x = x, y = y, color = g)) +
geom_point() +
geom_point(aes(x = x_transformed, y = y_transformed)) +
theme_minimal()
}
Run the code above in your browser using DataLab