# Some In/Out examples

This chapter gives some examples of how to pass values from R to cpp and vice versa. There is a high degree of flexibility.

Pass a list

A list can contain different classes of objects. here we want to pass the following list to a C++ function which does nothing else but returning all the objects with a slightly different name in a newly created list.

mylist = list(A = array(1:10,c(10,1)),
              a = pi,
              b = FALSE,
              C = matrix(rnorm(20),4,5))

You can see that have 4 different classes here: a vector, a double, a boolean and a matrix. Let's pass it to C++:

library(Rcpp)
library(inline)

src2 <- '
    List l(inlist);
    NumericVector one = as<NumericVector>(l["A"]);
    double two = as<double>(l["a"]);
    bool three = as<bool>(l["b"]);
    NumericMatrix four = as<NumericMatrix>(l["C"]);
    // do something useful here
    // ...
    // put together into a list
    // notice: if not using the inline package, must declare
    // namespace Rcpp, or prepend all Rcpp functions with
    // Rcpp::
    List outlist = List::create( _["A.out"] = one, _["a.out"] = two, _["b.out"] = three, _["C.out"] = four);
    return outlist;
    '

f3 <- cxxfunction(signature(inlist="List"),body=src2,plugin="Rcpp")

f3(inlist=mylist)
## $A.out
##       [,1]
##  [1,]    1
##  [2,]    2
##  [3,]    3
##  [4,]    4
##  [5,]    5
##  [6,]    6
##  [7,]    7
##  [8,]    8
##  [9,]    9
## [10,]   10
## 
## $a.out
## [1] 3.142
## 
## $b.out
## [1] FALSE
## 
## $C.out
##         [,1]     [,2]    [,3]    [,4]    [,5]
## [1,] -1.0264 -0.72960 -2.3014  1.1323 -1.4983
## [2,] -1.2078  0.63080  0.4601  0.4494  0.2478
## [3,]  1.3585  0.06326  0.1775 -1.1889  0.6780
## [4,]  0.3557 -0.60087 -0.7089  0.0578  1.0387
comments powered by Disqus