简体   繁体   中英

Create multiple vectors from list elements and apply a function in R?

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: 示例拼凑图

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM