Skip to content
Prev 379971 / 398500 Next

R C API resize matrice

Hi,

I don't think there is a native R API to do what you want here, but if the
matrix is only used by you and not be exported to the other user, you can
hack R data structure to achieve that goal.

Because there is not too much context of your question, I will assume the
whole point of resizing a matrix is to avoid the overhead of memory
allocation, not to represent the same matrix with different dimension since
your 'new' matrix has a different number of elements.

Roughly speaking, a matrix in R is nothing but a vector with a dim
attribute, you can verify it by R code:
```
[,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
$dim
[1] 2 3
[1] 1 2 3 4 5 6
```
Therefore, in order to resize the matrix, you need to change the dim
attribute( to a smaller size). Unfortunately, R does its best to prevent
you from doing such dangerous operation( and you should know this is* not
correct!*), you have to go to the C level to hack R internal data
structure. Let's say you want to resize the matrix A to a 2-by-2 matrix,
here is what you need to do:

C code:
The code sets the second value of the dim attribute to 2.
```
// [[Rcpp::export]]
void I_know_it_is_not_correct(SEXP x,SEXP attrName) {
INTEGER(Rf_getAttrib(x, attrName))[1]=2;
}
```

R code:
```
[,1] [,2]
[1,]    1    3
[2,]    2    4
$dim
[1] 2 2
```

You get what you want. Please use it with your caution.

Best,
Jiefei


On Fri, Jun 14, 2019 at 2:41 PM Morgan Morgan <morgan.emailbox at gmail.com>
wrote: