3

I'm trying to re-assign values by index in a (fairly) large array in R. However, it seems wildly slow. Is there a faster way to run this?

For example, for me re-assigning just one value in my array takes 30 seconds.

my_array <- array(1:2.5e8, dim = c(5e3, 5e3, 1e2))
system.time({
    my_array[1,1,1] <- 2
})
   user  system elapsed 
  4.750   4.465  30.664 
Molly OW
  • 113
  • 8
  • 6
    I suspect this is because you're creating an `integer` array with your `1:2.5e8` syntax but when you assign the `numeric` value `2` to it, then the whole array is copied as a new, numeric array. Do you still see this delay if you do `my_array[1,1,1] <- 2L`? – SamR Mar 27 '23 at 08:02
  • 1
    @SamR Well spotted, alternatively create a double array `array(as.double(1:2.5e8), dim=c(5e3, 5e3, 1e2))` if a double is to be assigned. – jay.sf Mar 27 '23 at 08:09
  • @SamR this works! If you want to add it as an answer I will accept. – Molly OW Mar 27 '23 at 17:09
  • @MollyOW thanks but now we know what the issue is I think I have found a duplicate (though with vectors rather than arrays). I'll raise a duplicate flag and if you think it's the same issue you can close it. – SamR Mar 27 '23 at 17:22

0 Answers0