[Rcpp-devel] Splitting a matrix by its rows into a list

Søren Højsgaard sorenh at math.aau.dk
Tue Feb 19 00:37:42 CET 2013


I want to split a matrix by its rows into a list as:
> a<- matrix(letters[1:6],ncol=2)
> split(a,row(a))
$`1`
[1] "a" "d"

$`2`
[1] "b" "e"

$`3`
[1] "c" "f"

I do as follows and get a strange result. Any suggestions?

Thanks in advance!
Søren

--------------- 

src <- '
  CharacterMatrix X(XX_);
  int Nx = X.nrow();
  List ans;
  for (int ii=0; ii<Nx; ii++){
    ans.push_back(X.row(ii));
  }
  return(wrap(ans));
'
split_ <- cxxfunction(signature(XX_="matrix"), plugin="Rcpp", body=src)

split_(a)

[[1]]
[[1]][[1]]
<CHARSXP: "a">

[[1]][[2]]
<CHARSXP: "d">


[[2]]
[[2]][[1]]
<CHARSXP: "b">

[[2]][[2]]
<CHARSXP: "e">


[[3]]
[[3]][[1]]
<CHARSXP: "c">

[[3]][[2]]
<CHARSXP: "f">




More information about the Rcpp-devel mailing list