c++ - Rcpp 通过 NumericVector 选择/子集 NumericMatrix 列
问题描述
我可以选择矩阵的所有行和矩阵的一系列列,如下所示:
library(Rcpp)
cppFunction('
NumericMatrix subset(NumericMatrix x){
return x(_, Range(0, 1));
}
')
但是,我想根据 a 选择列NumericVector y
,例如,可能类似于c(0, 1, 0, 0, 1)
. 我试过这个:
library(Rcpp)
cppFunction('
NumericMatrix subset(NumericMatrix x, NumericVector y){
return x(_, y);
}
')
但它不编译。我该怎么做?
解决方案
唉,Rcpp对非连续视图或在单个语句中仅选择第 1 列和第 4 列没有很好的支持。如您所见,选择连续视图或选择所有列可以使用Rcpp::Range()
. 您可能希望升级到RcppArmadillo以更好地控制矩阵子集。
RcppArmadillo 子集示例
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat matrix_subset_idx(const arma::mat& x,
const arma::uvec& y) {
// y must be an integer between 0 and columns - 1
// Allows for repeated draws from same columns.
return x.cols( y );
}
// [[Rcpp::export]]
arma::mat matrix_subset_logical(const arma::mat& x,
const arma::vec& y) {
// Assumes that y is 0/1 coded.
// find() retrieves the integer index when y is equivalent 1.
return x.cols( arma::find(y == 1) );
}
测试
# Sample data
x = matrix(1:15, ncol = 5)
x
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 4 7 10 13
# [2,] 2 5 8 11 14
# [3,] 3 6 9 12 15
# Subset only when 1 (TRUE) is found:
matrix_subset_logical(x, c(0, 1, 0, 0, 1))
# [,1] [,2]
# [1,] 4 13
# [2,] 5 14
# [3,] 6 15
# Subset with an index representing the location
# Note: C++ indices start at 0 not 1!
matrix_subset_idx(x, c(1, 3))
# [,1] [,2]
# [1,] 4 13
# [2,] 5 14
# [3,] 6 15
纯 Rcpp 逻辑
如果您不想承担犰狳的依赖性,那么 Rcpp 中矩阵子集的等价物是:
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::NumericMatrix matrix_subset_idx_rcpp(
Rcpp::NumericMatrix x, Rcpp::IntegerVector y) {
// Determine the number of observations
int n_cols_out = y.size();
// Create an output matrix
Rcpp::NumericMatrix out = Rcpp::no_init(x.nrow(), n_cols_out);
// Loop through each column and copy the data.
for(unsigned int z = 0; z < n_cols_out; ++z) {
out(Rcpp::_, z) = x(Rcpp::_, y[z]);
}
return out;
}
推荐阅读
- css - 在 CSS 选择器中合并元素
- html - 使用 Bootstrap 中的单选按钮更改标签字体大小时的对齐问题
- azure - Azure 应用服务上的 Asp.Net Core 2.2 TLS 1.2 支持
- java - 如何映射此复合主键?
- javascript - 如何使用 rxJS 根据当前属性向数组中的所有对象添加属性
- python - 如何识别增加值窗口的第一个索引?
- html - 标题内部的CSS垂直对齐中心
- c# - 如何查看本地 Git 存储库的头部更改?
- python-3.x - etree.fromstring(response.text.encode('utf-8'), parser=etree.XMLParser(huge_tree=self.huge_tree))
- python - 如何计算给定的经度和纬度是否属于多边形区域?