This page is tested only in R version newer than 2.4
---
- Reference
- GSL -- GNU Scientific Library.
- For MS Windows,
the GSL has binaries and setup for MinGW,
and it can be installed as MinGW's library.
See
GnuWin32 packages for the detail.
(my mirror here
for GSL version 1.8).
- Call GSL
First, create a C code file
"gsltools.c"
contains the following, it will list all possible permutations
for a given integer n (*nrow) by calling the GSL functions.
See the GSL document for the detail.
```
/*
File name: gstools.c
For Linux,
SHELL> gcc -c gsltools.c; gcc -shared -o gsltools.so gsltools.o -lgsl -lgslcblas
For MS Windows,
SHELL> gcc -c gsltools.c
SHELL> gcc -shared -o gsltools.dll gsltools.o -lgsl -lgslcblas
*/
#include <gsl/gsl_permutation.h>
int allpermu(int *nrow, int *all){
gsl_permutation *p;
int i, j;
p = gsl_permutation_alloc(*nrow);
gsl_permutation_init(p);
i = 0;
do{
for(j = 0; j < *nrow; j++){
*(all + i + j) = (int) gsl_permutation_get(p, (size_t) j);
}
i += *nrow;
}
while(gsl_permutation_next(p) == GSL_SUCCESS);
gsl_permutation_free (p);
return 0;
}
```
Create an R code file
"callgsl.r"
contains this
```
# File name: callgsl.r
dyn.load("/usr/lib/libgslcblas.so", local = FALSE, now = FALSE)
dyn.load("/usr/lib/libgsl.so", local = FALSE, now = FALSE)
dyn.load("gsltools.so")
### For MS Windows, they will be like these
# dyn.load("C:/PROGRA~1/RTOOLS/MINGW/BIN/LIBGSLCBLAS.DLL")
# dyn.load("C:/PROGRA~1/RTOOLS/MINGW/BIN/LIBGSL.DLL")
# dyn.load("gsltools.dll")
allpermu <- function(n){
# if(n > 10) stop("allpermu: n <= 10")
ncol <- as.integer(factorial(n))
nrow <- as.integer(n)
all <- vector(mode = "integer", length = nrow * ncol)
ret <- .C("allpermu", nrow, all)[[2]]
matrix(ret, nrow = nrow) + 1
}
allpermu(3)
dyn.unload("gsltools.so")
dyn.unload("/usr/lib/libgsl.so")
dyn.unload("/usr/lib/libgslcblas.so")
### For MS Windows, they will be like these
# dyn.unload("gsltools.dll")
# dyn.unload("C:/PROGRA~1/RTOOLS/MINGW/BIN/LIBGSL.DLL")
# dyn.unload("C:/PROGRA~1/RTOOLS/MINGW/BIN/LIBGSLCBLAS.DLL")
```
For MS Windows, the compiled gstools.dll can be donloaded at
here.
- Output
Each column contains one possible permutation. For n = 3,
there are 3! = 6 possible outcomes.
```
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 2 3 3
[2,] 2 3 1 3 1 2
[3,] 3 2 3 1 2 1
```
- Conclusion
- Call by address in R.
- Use a column-wise data structure in R and Fortran.
- Use a row-wise data structure in C.
- Use pointers in C to catch the objects' address which are passed from R.
- Use dyn.load() to load the GSL in R.
---