计算三个列表中的数字并生成一个大列表

Compute numbers in three lists and generate a big list

我需要用 A 中的每个数字计算 B 中的每个数字,用 fun 中的公式计算 m0 中的每个数字。通过应用 ge <- lapply(B,fun),如果 m0 是单个数字,我可以用 B 中的每个数字计算 A 中的每个数字。如果我现在有超过一个m0怎么办?

我认为即使计算各种 BA 但单个 m0,我在这里用函数 lapply 然后 lapply 所做的再次不是一个聪明的方法。

预期输出是一个列表,其中 B 中的值是用 Am0 的不同数量计算得出的。

这是 ge 的结构,当 m0 是单个值时。


fun <- function (i){
  res <- lapply(A, function(x){
    g <- as.matrix (m0 * (-x * i))})}
ge <- lapply(B, fun)

m0 <- c(10,20)
A <- c(1,2)
B <- list(per1 = structure(list(t1 = c(1,2), t2 = c(3,4)), row.names = c(NA, 
                                                                        -2L), class = "data.frame"),
          per2 = structure(list(t1 = c(10,20), t2 = c(30,40)), row.names = c(NA, 
                                                                         -2L), class = "data.frame"))

如果我理解正确的话

基础

m0 <- c(10, 20)
A <- c(1,2)
B <- list(
  per1 = structure(list(t1 = c(1, 2), t2 = c(3, 4)),
    row.names = c(NA, -2L),
    class = "data.frame"
  ),
  per2 = structure(list(t1 = c(10, 20), t2 = c(30, 40)),
    row.names = c(NA, -2L),
    class = "data.frame"
  )
)

fun <- function (i){
  lapply(A, function(x){
    lapply(m0, function(y) y * (-x * i)
    )
  }
  )
}

lapply(B, fun)
#> $per1
#> $per1[[1]]
#> $per1[[1]][[1]]
#>    t1  t2
#> 1 -10 -30
#> 2 -20 -40
#> 
#> $per1[[1]][[2]]
#>    t1  t2
#> 1 -20 -60
#> 2 -40 -80
...

reprex package (v1.0.0)

于 2021 年 2 月 10 日创建

使用 tidyverse 1

library(tidyverse)
m0 <- c(10, 20)
A <- c(1, 2)
B <- list(
  per1 = structure(list(t1 = c(1, 2), t2 = c(3, 4)),
    row.names = c(NA, -2L),
    class = "data.frame"
  ),
  per2 = structure(list(t1 = c(10, 20), t2 = c(30, 40)),
    row.names = c(NA, -2L),
    class = "data.frame"
  )
)
df_expand <- expand_grid(A, m0, B) 

fn <- function(A, m0, B) {
  m0 * (-A * B)
}

res <- pmap(df_expand, fn)
nm <- with(df_expand, paste0(names(B), "-A", A, "-m0_",m0))
purrr::set_names(res, nm)
#> $`per1-A1-m0_10`
#>    t1  t2
#> 1 -10 -30
#> 2 -20 -40
#> 
#> $`per2-A1-m0_10`
#>     t1   t2
#> 1 -100 -300
#> 2 -200 -400

reprex package (v1.0.0)

于 2021 年 2 月 10 日创建

使用 tidyverse 2

library(tidyverse)
m0 <- c(10, 20)
A <- c(1, 2)
B <- list(
  per1 = structure(list(t1 = c(1, 2), t2 = c(3, 4)),
                   row.names = c(NA, -2L),
                   class = "data.frame"
  ),
  per2 = structure(list(t1 = c(10, 20), t2 = c(30, 40)),
                   row.names = c(NA, -2L),
                   class = "data.frame"
  )
)
map(m0, function(z) map(-A, function(x) map(B, function(y) x * y * z)))  
#> [[1]]
#> [[1]][[1]]
#> [[1]][[1]]$per1
#>    t1  t2
#> 1 -10 -30
#> 2 -20 -40
#> 
#> [[1]][[1]]$per2
#>     t1   t2
#> 1 -100 -300
#> 2 -200 -400

reprex package (v1.0.0)

于 2021 年 2 月 10 日创建