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

Kevin Ushey kevinushey at gmail.com
Tue Feb 19 02:02:49 CET 2013


One solution: X.row(ii) is actually generating a CharacterMatrix::Row ; ie,
a view of that row in the CharacterMatrix, and I think you need to
explicitly copy it to a CharacterVector and then assign that
CharacterVector to the list.

You could write something like:

src <- '
  CharacterMatrix X(XX_);
  int Nx = X.nrow();
  List ans;
  for (int ii=0; ii<Nx; ii++) {
    CharacterMatrix::Row view = X.row(ii);
    CharacterVector tmp = no_init( X.ncol() );
    for( int j=0; j < X.ncol(); j++ ) {
      tmp[j] = view[j];
    }
    ans.push_back( tmp );
  }
  return(wrap(ans));
'

although it is a bit clunkier. I'm not sure if there's a more idiomatic
method available.

FWIW, trying to copy and assign directly, e.g. 'CharacterVector tmp =
X.row(ii);', doesn't seem to work, even though the same code works (and is
in the quick-start vignette) for NumericVector.

-Kevin

On Mon, Feb 18, 2013 at 3:37 PM, Søren Højsgaard <sorenh at math.aau.dk> wrote:

> 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">
>
>
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20130218/463c0872/attachment.html>


More information about the Rcpp-devel mailing list