我开始使用tidyversemap()
函数来构建包含嵌入的数据帧和矩阵的列表.下面的代码创建createBucketMap()
函数,该函数很好地计算所呈现的多个数据帧的前两列("inflow"和"Due"),如下面的第一张图像所示,用于第一个呈现的数据帧,其计算利用createBucketMap()
函数外部的列表和向量,每行代码alc <- allocate[[matL_name]]
和rate <- rates[[matL_name]]
.
现在,我try 将使用计算值填充其余数据帧列的代码插入到createBucketMap()
函数中,因为该函数构建了数据帧.在下面的代码中,您可以在我的注释中看到我试图让每个呈现的DataFrame列执行的操作.我的初学者倾向于使用map()
之外的一系列dplyr
mutate()
语句来添加具有以"cover_Due"到"outflow"开头的相关计算的列,但这看起来很笨拙.有没有一种干净的方法来使用map()
或任何其他tidyverse
函数来填充这些数据帧列,这些函数与下面代码中使用的map()
struct 一致?
我试图包括的这些计算列是内部数据帧计算,因为它们引用了同一数据帧中的其他列,而不是数据帧之外的列.这是mutate()
人擅长的事情.
只需对"COVER_DUE"列进行一个示例计算,即可获得所需的入门知识."COVER_DUE"应等于"INFLOW"和"DUBLE"同一行中较小的值.
下面是在此操作中运行map()
代码时呈现的第一个列表/数据框项,其中只计算和填充前两列:
下面是一个冗长而笨拙的for-loop解决方案的正确输出,该解决方案没有使用map()
,并且所有字段都被正确计算和填充:
代码:
seriesVector <- function() {c("mat_One", "mat_Two")}
matList <- list(mat_One = c("Boy", "Cat"), mat_Two = c("Boy", "Bat"))
allocate <- list(mat_One = c(0.6, 0.5, 0.4), mat_Two = c(0.4, 0.5, 0.6))
flowVector <- c(6, 5, 600) # was 4
balVector <- c(1000, 900, 800)
rates <- list(mat_One = 0.10, mat_Two = 0.20)
library(tidyverse)
createBucketMap <- function() {
imap(matList, \(matL, matL_name) {
map(matL, \(x) {
alc <- allocate[[matL_name]]
rate <- rates[[matL_name]]
data.frame(
Inflow = flowVector * alc,
Due = balVector * alc * rate,
Cover_due = 0, # minimum of Inflow and Due in the same row
Shortfall = 0, # equal to “Due” minus “Cover_due” in the same row
Begin_cum_shortfall = 0, # equal to prior (lagged) row of col “End_cum_shortfall” except that in row 1 “Begin_cum_shortfall” is zero
Cover_cum_sfall = 0, # equal to lesser of (a) “Inflow” minus “Cover_due” and (b) “Begin cum_shortfall”, all in the same row
End_cum_shortfall = 0, # equal to “Shortfall” plus “Begin_cum_shortfall” minus “Cover_cum_sfall” all in the same row
Outflow = 0 # equal to “Inflow” minus “Cover_due” minus “Cover_cum_sfall”, all in the same row
) |>
as.matrix()
}) |>
set_names(matL)
})
}
createBucketMap()