假设我有以下矩阵:
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
")))
该矩阵有列名V1
to V6
假设还有另一个矩阵,我在其中删除了列名称:
> testM2<-testM
> colnames(testM2)<-NULL
那么如果我尝试colMeans
on testM
and testM2
R 返回一个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;
}
输出为colMeansCppMt
对彼此而言testM
and testM2
返回数值向量,但该向量为testM
不包含colnames
因为它还没有被设置。
现在,假设我改变colMeansCppMt
函数包含这样的属性:
//[[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;
}
输出为testM
仍然是一个不包含列名称的向量。
我也尝试过out.attr("names")=x.attr("colnames")
and out.attr("colnames")=x.attr("colnames")
.
A)。我如何在 RCpp 中查看colnames
矩阵的(例如x
在上面的示例函数中)是否已设置?
b).如何返回 R 中名称为 Rcpp 的数字向量?