1

So my question relates to the following case:

Suppose I have a numeric matrix mat which has 10 rows and 10 columns. And I create a second matrix mat_filterwhich is supposed to specify the elements that should be modified.Lets say i want to modify elements in the positions: (1,1) (6,5) (10,3) Like so:

mat <- matrix(7,10,10)
mat_filter <- cbind(c(1,6,10),
                    c(1,5,3))

Now i try to modify mat :

mat[mat_filter] <- mat[mat_filter] + 1

my question is, what exactly is getting copied by R when I try to modify the specified matrix elements like this? Is the entire matrix getting copied? In general what I want to understand is where redundancies occur in these types of modifications, I know that using lists its possible to modify objects in place, also with individual vectors, but what about matrices? When I use the i,j indexing of the matrix, is that any different than using the single integer indexing of the matrix?

dvd280
  • 876
  • 6
  • 11
  • 1
    You can use `tracemem` to check copying, as described e.g. here: [Avoid copying the whole vector when replacing an element](https://stackoverflow.com/questions/18359940/avoid-copying-the-whole-vector-when-replacing-an-element-a1-2/18361181#18361181). Please note that (1) [RStudio may modify objects](https://stackoverflow.com/questions/15559387/operator-in-rstudio-and-r/15559956#15559956), and (2) from R 4.0.0 [Reference counting is used instead of the `NAMED` mechanism](https://cran.r-project.org/doc/manuals/r-release/NEWS.html) – Henrik May 15 '20 at 11:05

1 Answers1

1

It seems the object does not get copied in this case. You can use the base::tracemem() function:

mat <- matrix(7,10,10)
mat_filter <- cbind(c(1,6,10),
                    c(1,5,3))

tracemem(mat)
[1] "<0x7fa68bfde840>"

This returns the current memory address of mat, and will print any change in address, if one occurs.

mat[mat_filter] <- mat[mat_filter] + 1

produces no tracemem output, so the modification should be happening in place.

Hadley Wickham's Advanced R has a chapter on this.

thorepet
  • 421
  • 2
  • 9