我正在使用 RCPP 来加速我项目中的 R 代码。现在我正在做的是使用 Armadillo 包将我的 R 代码转换为 C++。我发现我经常用 C++ 编写多行来替换 R 中的一行...
这是我的问题: 我有一个 vector 存储数据:数据。我还有一个矩阵存储我需要访问的元素的索引。请允许我先用 R 说明我的场景:
> Data
[1] 4 5 6 7 8
和
> index
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 0 0
[3,] 2 0 2
对于“索引”矩阵的每一行,我想从数据中获取相应的元素。在 R 中,我只需要这样编码:
> Data[index[1,]]
[1] 4 5 6
> Data[index[2,]]
[1] 4
> Data[index[3,]]
[1] 5 5
即 我需要的“索引”矩阵第一行的元素是 Data[1],Data[2],Data[3]
我需要的“索引”矩阵第二行的元素是 资料[1]
我需要的“索引”矩阵第 3 行的元素是 数据[2] 数据[2]
R 的便利之处在于 R 会自动将 0 索引识别为“无”并且不会访问它。
现在我将 vector “数据”和矩阵“索引”输入到 C 中。我想知道有什么方法可以达到与上面 R 类似的结果吗?非常感谢!
最佳答案
基础 R
您可以使用索引对数据进行子集化,结果将是一个列表
Data <- c( 4 ,5 ,6, 7, 8)
index <- matrix(c(1,2,3, 1, 0, 0, 2,0,2), byrow = TRUE, nrow = 3)
apply(index, 1, function(x) Data[x])
# [[1]]
# [1] 4 5 6
#
# [[2]]
# [1] 4
#
# [[3]]
# [1] 5 5
结果将是矩阵
index <- matrix(c(1,2,3, 1, 0, 0, 2,0,2), byrow = TRUE, nrow = 3)
index[index == 0] <- NA
index
# [,1] [,2] [,3]
# [1,] 1 2 3
# [2,] 1 NA NA
# [3,] 2 NA 2
apply(index, 2, function(x) Data[x])
# [,1] [,2] [,3]
# [1,] 4 5 6
# [2,] 4 NA NA
# [3,] 5 NA 5
使用[
:
matrix( Data[index], nrow = 3, byrow = FALSE) # another way to get the same matrix
Rcpp:对于 0 索引,在 Data
vector 中使用 NA
您只需将 apply
转换为 Rcpp
代码,如 here 所述
或
使用[
:引用这个article有关使用 RCpp 进行 vector 子集化的更多信息
文件:mysubset.cpp
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector mysubset(NumericVector Data, NumericVector index) {
return Data[index];
}
RStudio:
library('Rcpp')
sourceCpp("mysubset.cpp")
Data <- c( NA, 4 ,5 ,6, 7, 8) # for 0 index, use NA
index <- matrix(c(1,2,3, 1, 0, 0, 2,0,2), byrow = TRUE, nrow = 3)
matrix( mysubset(Data, index), nrow = 3, byrow = FALSE)
# [,1] [,2] [,3]
# [1,] 4 5 6
# [2,] 4 NA NA
# [3,] 5 NA 5
mysubset(Data, index[1,])
# [1] 4 5 6
na.omit(mysubset(Data, index[2,]))
# [1] 4
关于c++ - 如何告诉 C++ 根据索引指示符放弃 vector 中的某些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48363724/