首页 > 解决方案 > 使用 apply 函数更新外部范围变量

问题描述

我正在尝试遍历 data.table 并对数据进行某些处理:

实际处理更复杂(每次应用迭代的输出中都包含记录)并且比我为这个问题简化的下面的代码体积更大。

但是,我看不到如何更新 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)

标签: rdata.table

解决方案


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

推荐阅读