[通常,我想将Rcpp的二维矩阵转换为R中的向量,使用“ as(m)”应该非常简单,但是,我仍然从R中得到矩阵,我想知道为什么吗?我应该在Rcpp中手动删除attr吗?
#include <Rcpp.h>
#include <string>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector matrix2vector(NumericMatrix m, const bool byrow=false){
NumericVector x;
if(byrow){
Rcout<< "warning: default by column\n";
m = transpose(m);
x = as<NumericVector>(m);
}else{
x = as<NumericVector>(m);
}
return(x);
}
/*** R
m=matrix(1:15,5,3)
matrix2vector(m,byrow=T)
*/
我不确定我是否理解问题或尝试的答案。您仍然在这里返回矩阵。而且Rcpp对重塑和更高级的Matrix操作的支持有限。
代码的简化版本:
码#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector matrix2vector(NumericMatrix m, const bool byrow=false){
if (byrow){
Rcout << "warning: default by column\n";
m = transpose(m);
}
return NumericVector(m);
}
/*** R
m <- matrix(1:15,5,3)
print(matrix2vector(m, byrow = TRUE))
print(matrix2vector(m, byrow = FALSE))
*/
输出量R> Rcpp::sourceCpp("~/git/stackoverflow/61036707/question.cpp")
R> m <- matrix(1:15,5,3)
R> print(matrix2vector(m, byrow = TRUE))
warning: default by column
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 6 7 8 9 10
[3,] 11 12 13 14 15
R> print(matrix2vector(m, byrow = FALSE))
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
R>
您实际上在这里执行的只是一个移调。
我会尝试RcppArmadillo,其中的[[does具有显式的rowvec
和colvec
类型,后者被别名为vec
。我必须检查一下将“按列排列”元素重塑为按列向量的行的建议。
[Edit:
在RcppArmadillo中确实确实(通常如此)更容易。码#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat matrix2vector(arma::mat m, const bool byrow=false){
if (byrow) {
return m.as_row();
} else {
return m.as_col();
}
}
/*** R
m <- matrix(1:15,5,3)
print(matrix2vector(m, byrow = TRUE))
print(matrix2vector(m, byrow = FALSE))
*/
输出量R> Rcpp::sourceCpp("~/git/stackoverflow/61036707/answer.cpp")
R> m <- matrix(1:15,5,3)
R> print(matrix2vector(m, byrow = TRUE))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
[1,] 1 6 11 2 7 12 3 8 13 4 9 14 5 10 15
R> print(matrix2vector(m, byrow = FALSE))
[,1]
[1,] 1
[2,] 2
[3,] 3
[4,] 4
[5,] 5
[6,] 6
[7,] 7
[8,] 8
[9,] 9
[10,] 10
[11,] 11
[12,] 12
[13,] 13
[14,] 14
[15,] 15
R>
请注意,我使用返回答案。arma::mat
作为返回类型不会与colvec
或rowvec
冲突。您可以选择其中一个,但随后您可以not
编辑2:
并根据以下评论:如果您真的只想重塑已经拥有的内容,则不需要Rcpp。只需核对dim
属性。在R(和C ++,如果需要)级别工作:R> m
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
R> dim(m)
[1] 5 3
R> dim(m) <- NULL
R> m
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
R>
我想要的如下:
#include <Rcpp.h>
#include <string>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector matrix2vector(NumericMatrix m, const bool byrow=false){
NumericVector x;
if(byrow){
Rcout<< "warning: default by column\n";
m = transpose(m);
}
NumericVector x(m);
x.attr("dim") = R_NilValue;
return(x);
}
/*** R
m=matrix(1:15,5,3)
matrix2vector(m,byrow=T)
# [1] 1 6 11 2 7 12 3 8 13 4 9 14 5 10 15
*/