在 R 中更新数据集的最快方法是什么?

2023-12-03

我有一个 20000 * 5 的数据集。目前它正在以迭代方式进行处理,并且数据集在每次迭代中不断更新。

data.frame 中的单元格每次迭代都会更新,并寻求一些帮助来更快地运行这些东西。由于这是一个小的 data.frame,我不确定 data.table 是否可以正常工作。

以下是 data.frame 子分配的基准:

sessionInfo()
R version 3.2.4 Revised (2016-03-16 r70336)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows Server >= 2012 x64 (build 9200)
set.seed(1234)
test <- data.frame(A = rep(LETTERS  , 800), B = rep(1:26, 800),    C=runif(20800), D=runif(20800) , E =rnorm(20800))
microbenchmark::microbenchmark(test[765,"C"] <- test[765,"C"] + 25)
Unit: microseconds
                                  expr     min       lq     mean   median       uq      max neval
 test[765, "C"] <- test[765, "C"] + 25 112.306 130.8485 979.4584 186.3025 197.7565 44556.15   100}

有没有办法比我发布的更快地实现上述功能?


有趣的是,如果您使用 data.table,乍一看似乎并没有更快。当在循环内部使用赋值时,也许它会变得更快。

library(data.table)
library(microbenchmark)
dt <- data.table(test)

# Accessing the entry
dt[765, "C", with = FALSE] 

# Replacing the value with the new one
# Basic data.table syntax
dt[i =765, C := C + 25 ]

# Replacing the value with the new one
# using set() from data.table
set(dt, i = 765L, j = "C", value = dt[765L,C] + 25)

microbenchmark(
      a = set(dt, i = 765L, j = "C", value = dt[765L,C] + 25)
    , b = dt[i =765, C := C + 25 ]
    , c = test[765, "C"] <- test[765, "C"] + 25
    , times = 1000       
  )

微基准测试结果:

                                                   expr     min      lq     mean  median       uq      max neval
 a = set(dt, i = 765L, j = "C", value = dt[765L, C] + 25) 236.357 46.621 266.4188 250.847 260.2050  572.630  1000
 b = dt[i = 765, `:=`(C, C + 25)]                         333.556 345.329 375.8690 351.668 362.6860 1603.482  1000
 c = test[765, "C"] <- test[765, "C"] + 25                73.051  81.805 129.1665  84.220  87.6915 1749.281  1000
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 R 中更新数据集的最快方法是什么? 的相关文章

随机推荐