簡體   English   中英

在 R 中更新數據集的最快方法是什么?

[英]What is the fastest way to update a data set in R?

我有一個 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

您可以從?set函數的手冊開始。 在示例中,您將找到可用於基准測試的代碼。 我只是重新運行它並得到以下時間。

library(data.table)
m = matrix(1, nrow = 2e6L, ncol = 100L)
DF = as.data.frame(m)
DT = as.data.table(m)    

system.time(for (i in 1:1000) DF[i, 1] = i)
#   user  system elapsed 
#  3.048   1.512  24.854
system.time(for (i in 1:1000) DT[i, V1 := i])
#   user  system elapsed 
#  0.232   0.000   0.259 
system.time(for (i in 1:1000) set(DT, i, 1L, i))
#   user  system elapsed 
#  0.000   0.000   0.002

理想情況下,您需要檢查數據的數據更新方案並進行擴展以正確衡量哪個是“最快的”。 另外一定要檢查內存使用情況,在矩陣上使用[<-似乎比 data.table 方式使用更多的內存,如果你最終交換它會更慢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM