这是我之前关于 使用
rnorm()
替换模拟变量的查询的分支。
现在,我面临着另一件棘手的事情,因为我是 R 的初学者。说:
# Values representing the number of simulations for each observation
simulations <- c(728, 680, 631, 583, 534, 486, 437, 388, 340, 291)
# Use lappy to generate the series of simulations for each observation
unit.cost <- lapply(simulations, rnorm, mean = 8403.86, sd = 1000)
bldg.size <- lapply(simulations, rnorm, mean = 35, sd = 5)
考虑到
mean
和 sd
对于 unit.cost
和 bldg.size
是恒定的,如何将每个观察的模拟变量相互相乘,返回乘积列表(相乘变量)。例如,在第一次观察时,将有 728 次 unit.cost
模拟和 728 次 bldg.size
模拟。我希望这些模拟相互相乘,以便得出一个名为“bldg.cost”的新变量来代表产品。
我还期望为每个观察生成“bldg.cost”的总和。最后,我应该有一个反映每个观察的“bldg.cost”总和的数据框。
您可以使用
Map
Map(function(x,y) x * y, unit.cost, bldg.size)
library(tidyverse)
bldg <- tibble(
simulations,
unit.cost = lapply(simulations, rnorm, mean = 8403.86, sd = 1000),
bldg.size = lapply(simulations, rnorm, mean = 35, sd = 5),
bldg.cost = Map(function(x,y) x * y, unit.cost, bldg.size),
) |>
unnest(cols=c(unit.cost, bldg.size, bldg.cost))
summarise(bldg, sum=sum(bldg.cost), .by=simulations)