[R] R C API resize matrice

King Jiefei @zwj|08 @end|ng |rom gm@||@com
Sat Jun 15 01:15:11 CEST 2019


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:
```
> A=matrix(1:6,2,3)
> A
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
> attributes(A)
$dim
[1] 2 3

> attributes(A)=NULL
> A
[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:
```
> a=matrix(1:6,2,3)
> I_know_it_is_not_correct(a,as.symbol("dim"))
> a
     [,1] [,2]
[1,]    1    3
[2,]    2    4
> attributes(a)
$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 using gmail.com>
wrote:

> Hi,
>
> Is there a way to resize a matrix defined as follows:
>
> SEXP a = PROTECT(allocMatrix(INTSXP, 10, 2));
> int *pa  = INTEGER(a)
>
> To row = 5 and col = 1 or do I have to allocate a second matrix "b" with
> pointer *pb and do a "for" loop to transfer the value of a to b?
>
> Thank you
> Best regards
> Morgan
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list