Rcpp中的成员函数nrow()

时间:2018-01-08 18:02:10

标签: r rcpp

让我们直截了当。以下是Rcpp示例,这是一个简单的例子。但是出现了一些疑问。

src4 <- '
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::plugins("cpp11")]]

// [[Rcpp::export]]
List rcpp_attributes(NumericVector v, NumericMatrix m, 
                     DataFrame df, List L) {

double nrows = 3;
double ncols = 3;
m.attr("dim") = NumericVector::create( nrows, ncols );

CharacterVector row_names = {"a", "b", "c"};
CharacterVector col_names = {"x", "y", "z"};
m.attr("dimnames") = List::create( row_names, col_names );

return List::create(
_["v.attr_names"] = v.attr("names"),     // Element names
_["v.names"] = v.names(),                // Element names
_["m.ncol"] = m.ncol(),                  // Number of columns
_["m.nrow"] = m.nrow(),                  // Number of rows
_["m.attr_dim"] = m.attr("dim"), 
_["m.attr_dimnames"] = m.attr("dimnames"),
_["df.attr_names"] = df.attr("names"),        // column names
_["df.attr_row.names"] = df.attr("row.names"), // row names
_["L.names"] = L.names(),            // Element names
_["m"] = m
);
}
'
sourceCpp(code = src4)
rcpp_attributes(c("s" = 1, "u" = 2, "k" = 3),
                matrix(1:9, 9, 1),
                data.frame(a = c("a1", "a2"),
                           b = c(   1, 3)),
                list("a" = c(1), "b" = c(1,2), "c" = c(1,2,3)))

返回结果如下:

## $v.attr_names
## [1] "s" "u" "k"
## 
## $v.names
## [1] "s" "u" "k"
## 
## $m.ncol
## [1] 3
## 
## $m.nrow
## [1] 9
## 
## $m.attr_dim
## [1] 3 3
## 
## $m.attr_dimnames
## $m.attr_dimnames[[1]]
## [1] "a" "b" "c"
## 
## $m.attr_dimnames[[2]]
## [1] "x" "y" "z"
## 
## 
## $df.attr_names
## [1] "a" "b"
## 
## $df.attr_row.names
## [1] 1 2
## 
## $L.names
## [1] "a" "b" "c"
## 
## $m
##   x y z
## a 1 4 7
## b 2 5 8
## c 3 6 9

从上面我们可以看到,$ m.ncol返回3,它是对的。然而, 元素$ m.nrow返回9.我认为它应该是3。 我希望有人写Rcpp代码可以告诉我原因吗? 谢谢!~~

0 个答案:

没有答案