r - 使用 apply 函数更新外部范围变量
问题描述
我正在尝试遍历 data.table 并对数据进行某些处理:
提供基于处理的每一行的组合输出的输出
在一个名为 statsTable 的单独表中记录处理的各种详细信息,该表在该过程的此阶段和其他阶段得到更新
实际处理更复杂(每次应用迭代的输出中都包含记录)并且比我为这个问题简化的下面的代码体积更大。
但是,我看不到如何更新 statsTable,因为 lapply 可以防止这种情况发生(通过设计,我相信函数不会产生意想不到的后果 - 因此处理时间保持为零)。有没有办法做到这一点并且仍然使用其中一个应用功能?我知道我可以使用 for 循环,但如果可能的话,我不想这样做。
mainTable <- data.table(year = rep(2016:2020), value = runif(5, min=0, max=50000000))
statsTable <- data.table(year = rep(2016:2020), procTime = 0)
setkey(statsTable, year)
output <- bind_rows(lapply(mainTable$year, function(fileYear) {
randomValue = as.integer(mainTable[year == fileYear]$value)
print(paste0(fileYear, ":", randomValue))
start <- proc.time()[[3]]
for(i in 1:randomValue) {}
elapsed = proc.time()[[3]]- start
statsTable[year == fileYear]$procTime = elapsed
print(elapsed)
data.table(year = fileYear, loopsPerSecond = randomValue / elapsed)
}))
print(output)
print(statsTable)
解决方案
One way to reach a variable outside apply
functions could be the <<-
operator, which reaches the parent environments. if you change the line
statsTable[year == fileYear]$procTime <- elapsed
to
statsTable[year == fileYear]$procTime <<- elapsed
you should be able to update the statsTable
variable.
# print(statsTable)
# year procTime
# 1: 2016 1.071
# 2: 2017 0.496
# 3: 2018 0.623
# 4: 2019 0.771
# 5: 2020 0.941
推荐阅读
- python - Pandas 将列单热编码为假人,包括“其他”编码
- javascript - 如何将 Material UI 的 HOC 组合在一起
- javascript - Node js new Date() 和 Browser new Date() 给出不同的日期
- javascript - 安全数学课。如何创建可链接的计算?
- flutter - 如何在flutter中使用一个streamBuilder从firestore中检索文本和图像?
- laravel - 如何过滤 laravel 模型关系,如果关系为空/null,则不应显示对象
- javascript - 如何使用javascript异步加载链接?
- java - 在预算内选择可能的菜单项组合的算法或解决方案
- python - pip 与 conda 中的冲突解决
- java - 任何对象值更改的侦听器?