Avoid copying the whole vector when replacing an element (a[1] <- 2)

后端 未结 2 1147
情深已故
情深已故 2021-01-04 12:15

When replacing an element in a vector such as

a <- 1:1000000
a[1] <- 2

R copies the whole vector, replaces the element in the new vec

2条回答
  •  抹茶落季
    2021-01-04 12:41

    You can do this with the ff package which is on CRAN. Using ff, your data is stored on disk and indexing will only affect that specific element you are indexing

    require(ff)
    a <- ff(1:1000000)
    a[1] <- 2
    

    For info. These are timings, so it is a lot faster for your toy case.

    require(ff)
    a <- 1:100000000
    b <- ff(a)
    system.time(a[1] <- 2)
     user  system elapsed 
    0.440   0.592   1.056 
    system.time(b[1] <- 2)
     user  system elapsed 
    0.004   0.000   0.001 
    

提交回复
热议问题