1

Using SEXP as argument of a function don't allows user to exchange data between them by simple assignement. I used to copy each value with a tmp buffer to perform swapping. My question is :there is a possibilty to write a function that only swap data like this:

// [[Rcpp::export]]
void  swap(SEXP x, SEXP y){
  std::swap(x,y);

} 

Then if I run this function with R, x and y will be swapped ?

MACHERKI M E
  • 131
  • 9
  • 1
    No, but you could write a helper function that does. I would not put such a helper the in `std` namespace as the `SEXP` you want this for is very _non_-standard, R specific and written in C. In short there is a bit of mismatch between your types here. – Dirk Eddelbuettel Mar 03 '19 at 15:12
  • I use std::copy all the time to make a fast copy but it takes a lot of time and space. I tried also to exchange symbol but it does not work. – MACHERKI M E Mar 03 '19 at 15:16

1 Answers1

6

Your code will not swap x and y.

Note that we don't need Rcpp to swap x and y without copying. We can do it in straight R as the following illlustrates. x originally has the address 0x16d9fa08 and y originally has the address 0x170291d8 and after the swap, done in R, their addresses are exchanged and everything under them stays with the addresses originally associated with the same parent addresses, i.e. the content is at the original addresses and has not been copied.

library(pryr)

x <- data.frame(a = 1:2)
y <- data.frame(y = 3:4)

inspect(x)
## <VECSXP 0x16d9fa08>
##   <INTSXP 0x1459a5b0>
## attributes: 
##   <LISTSXP 0x1203a7c0>
## ...snip...

inspect(y)
## <VECSXP 0x170291d8>
##   <INTSXP 0x12039288>
## attributes: 
##   <LISTSXP 0x14894a10>
## ...snip...

tmp <- x
x <- y
y <- tmp

inspect(x)
## <VECSXP 0x170291d8>
##   <INTSXP 0x12039288>
## attributes: 
##   <LISTSXP 0x14894a10>
## ...snip...

inspect(y)
## <VECSXP 0x16d9fa08>
##   <INTSXP 0x1459a5b0>
## attributes: 
##   <LISTSXP 0x1203a7c0>
## ...snip...
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341