Home > Back-end >  Create multiple vectors from list elements and apply a function in R?
Create multiple vectors from list elements and apply a function in R?

Time:11-08

For this problem, I'm trying to create multiple vectors that I can apply a function on. The function im using is patchwork::area.

For example, if I were to explicitly write out a design area to plot using patchwork I would do something like this:

library(patchwork)

# Explicitly writing out each area
design <- c(
  area(1, 1, 9, 9),
  area(1,10),
  area(2,10),
  area(3,10),
  area(4,10),
  area(5,10),
  area(6,10),
  area(7,10),
  area(8,10),
  area(9,10)
)

# example of what the plot area would look like
plot(design)

And this would look like: example patchwork plot

Essentially, I am trying to automate the design vector above. I attempted this by using lapply to create a list of areas, like so:

# create some data
vals = seq(1:9)
maxVal <- max(vals)

# use lapply 
areaList <- lapply(vals, function(x) area(x, maxVal 1))

This creates a list of the areas, excluding the first row from the design object above... but I cant figure out how to turn it into the design object above.

A naive attempt (that doesn't work) is to do something like the code below (which tries to include the 1st row of the design object)

designTest <- c(area(1, 1, maxVal, maxVal), 
                areaList)

Any suggestion as to how I could achieve this?

CodePudding user response:

You need to combine the elements of areaList like this before plotting:

library(patchwork)
library(purrr)

vals = seq(1:9)
maxVal <- max(vals)

areaList <- lapply(vals, function(x) area(x, maxVal 1))
a <- reduce(areaList, c)

plot(a)

This should work!

  • Related