在Rcpp中-如何返回带有名称的向量
假设我有以下矩阵:在Rcpp中-如何返回带有名称的向量,r,rcpp,R,Rcpp,假设我有以下矩阵: testM <- as.matrix(read.table(textConnection(" 1 5 4 1 3 2 2 1 5 4 1 3 2 2 1 5 4 1 3 2 2 1 5 4 1 3 2 2 1 5 4 1 3 2 2 1 1 5 4 1 3 2 2 1 5 4 1 3 2 2 1 5 4 1 3 2 2 1 5 4 1 3 2 2 1 5 4
testM <- as.matrix(read.table(textConnection("
1 5 4 1 3 2
2 1 5 4 1 3
2 2 1 5 4 1
3 2 2 1 5 4
1 3 2 2 1 5
4 1 3 2 2 1
1 5 4 1 3 2
2 1 5 4 1 3
2 2 1 5 4 1
3 2 2 1 5 4
1 3 2 2 1 5
4 1 3 2 2 1
")))
然后,如果我在testM
和testM2
R上尝试colMeans
,则在这两种情况下都返回numeric
类,但在第一种情况下,答案为colnames
> colMeans(testM)
V1 V2 V3 V4 V5 V6
2.166667 2.333333 2.833333 2.500000 2.666667 2.666667
> colMeans(testM2)
[1] 2.166667 2.333333 2.833333 2.500000 2.666667 2.666667
现在假设我在RCpp中编写了相同的函数,如下所示:
double do_mean(NumericVector x) {
return mean(na_omit(x));
}
//[[Rcpp::export]]
NumericVector colMeansCppMt(NumericMatrix& x) {
int nCols=x.ncol();
NumericVector out=no_init(nCols);
for (int i=0;i<nCols;i++) {
NumericMatrix::Column tmp=x(_,i);
out[i]=do_mean(tmp);
}
return out;
}
testM
的输出仍然是一个不包含列名的向量
我还尝试了out.attr(“name”)=x.attr(“colnames”)
和out.attr(“colnames”)=x.attr(“colnames”)
a) 。如果矩阵的colnames
已设置(例如,上述示例函数中的x
),如何在RCpp中进行检查
b) 。如何使用Rcpp中的名称返回R中的数字向量?要设置横向:
names
属性data.frame
s有一个row.names
属性用于行,而names
属性用于列,以及matrix
s有一个(可选)dimnames
属性;此属性是一个列表
,包含2个字符向量(行然后列)x
的列名附加到out
的“names”属性,例如:
out.attr("names") = VECTOR_ELT(x.attr("dimnames"), 1);
会有用的
(我想不起来,Rcpp
是否有一个很好的API来获取/设置数组中的维度名称…)
//[[Rcpp::export]]
NumericVector colMeansCppMt(NumericMatrix& x) {
int nCols=x.ncol();
NumericVector out=no_init(nCols);
for (int i=0;i<nCols;i++) {
NumericMatrix::Column tmp=x(_,i);
out[i]=do_mean(tmp);
}
out.attr("names")=x.attr("names");
return out;
}
out.attr("names") = VECTOR_ELT(x.attr("dimnames"), 1);