I have a df that contains coordinates to create a square:
library(ggplot2)
df = data.frame(xmin = 1, xmax = 3, ymin = 10, ymax = 15)
ggplot(df) +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = "green")

Now, I want to have a function, when it is given df, it adds new rows to the df, with 5 scaled versions of the original square, showing like this:

This means, the area of the green coloured squares in the new square(s) corresponds to the 5/9 of the original square.
I also want to make it recursively, so that, given the df with scaled version (5 squares, like in the second image) it gives:

and so on.
Using a recursive approach you could do:
square5 <- function(xmin, xmax, ymin, ymax) {
x <- data.frame(
xmin = c(0, rep(1/3, 3), 2/3),
xmax = c(0, rep(1/3, 3), 2/3) + 1/ 3,
ymin = c(1/3, 0, 1/3, 2/3, 1/3),
ymax = c(1/3, 0, 1/3, 2/3, 1/3) + 1/ 3
)
x[c("xmin", "xmax")] <- lapply(x[c("xmin", "xmax")], scales::rescale, to = c(xmin, xmax), from = c(0, 1))
x[c("ymin", "ymax")] <- lapply(x[c("ymin", "ymax")], scales::rescale, to = c(ymin, ymax), from = c(0, 1))
return(x)
}
df = data.frame(xmin = 1, xmax = 3, ymin = 10, ymax = 15)
df1 <- purrr::reduce(seq(5), function(x, n) purrr::pmap_df(x, square5), .init = df)
library(ggplot2)
ggplot(df1) +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = "green", color = "darkgreen", size = .5)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With