22//
33// Matrix.h: Rcpp R/C++ interface class library -- matrices
44//
5- // Copyright (C) 2010 - 2014 Dirk Eddelbuettel and Romain Francois
5+ // Copyright (C) 2010 - 2015 Dirk Eddelbuettel and Romain Francois
66//
77// This file is part of Rcpp.
88//
@@ -376,7 +376,6 @@ Matrix<REALSXP, StoragePolicy> transpose(const Matrix<REALSXP, StoragePolicy> &
376376 if (j > l_1) j -= l_1;
377377 s[i] = x[j];
378378 }
379- // Rf_copyMostAttrib((*this), r);
380379
381380 // there must be a simpler, more C++-ish way for this ...
382381 SEXP rnames = internal::DimNameProxy (x, 0 );
@@ -409,7 +408,6 @@ Matrix<INTSXP, StoragePolicy> transpose(const Matrix<INTSXP, StoragePolicy> & x)
409408 if (j > l_1) j -= l_1;
410409 s[i] = x[j];
411410 }
412- // Rf_copyMostAttrib((*this), r);
413411
414412 // there must be a simpler, more C++-ish way for this ...
415413 SEXP rnames = internal::DimNameProxy (x, 0 );
@@ -426,6 +424,37 @@ Matrix<INTSXP, StoragePolicy> transpose(const Matrix<INTSXP, StoragePolicy> & x)
426424 return r;
427425}
428426
427+ template <template <class > class StoragePolicy >
428+ Matrix<STRSXP, StoragePolicy> transpose (const Matrix<STRSXP, StoragePolicy> & x) {
429+ typedef Matrix<STRSXP, StoragePolicy> MATRIX;
430+ typedef Vector<STRSXP, StoragePolicy> VECTOR;
431+
432+ Vector<INTSXP, StoragePolicy> dims = ::Rf_getAttrib (x, R_DimSymbol);
433+ int nrow = dims[0 ], ncol = dims[1 ];
434+ MATRIX r (Dimension (ncol, nrow)); // new Matrix with reversed dimension
435+ R_xlen_t len = XLENGTH (x), l_1 = XLENGTH (x)-1 ;
436+
437+ // similar approach as in R: fill by in column, "accessing row-wise"
438+ VECTOR s = VECTOR (r.get__ ());
439+ for (R_xlen_t i = 0 , j = 0 ; i < len; i++, j += nrow) {
440+ if (j > l_1) j -= l_1;
441+ s[i] = x[j];
442+ }
443+
444+ // there must be a simpler, more C++-ish way for this ...
445+ SEXP rnames = internal::DimNameProxy (x, 0 );
446+ SEXP cnames = internal::DimNameProxy (x, 1 );
447+ if (!Rf_isNull (rnames) || !Rf_isNull (cnames)) {
448+ SEXP dimnames;
449+ PROTECT (dimnames = Rf_allocVector (VECSXP, 2 ));
450+ SET_VECTOR_ELT (dimnames, 0 , cnames);
451+ SET_VECTOR_ELT (dimnames, 1 , rnames);
452+ // do we need dimnamesnames ?
453+ Rf_setAttrib (r, R_DimNamesSymbol, dimnames);
454+ UNPROTECT (1 ); /* dimnames */
455+ }
456+ return r;
457+ }
429458
430459}
431460
0 commit comments