ベクトル内の特定の要素の出現をカウントできるRcppによって呼び出されるC ++カウントアルゴリズム。テンプレートを使用する必要があります。私の試み:
countRcpp <-'
#include<iostream>
#include<vector>
using namespace std;
int val = as<int>(y);
NumericVector xx(x);
NumericVector::iterator iter;
int m = 0;
for(iter = xx.begin(); iter < xx.end(); iter++){
if(*iter == val) ++m;}
return(wrap(m));
'
countf <- cxxfunction(signature(x = "numeric", y = "numeric"),
body = countRcpp,
plugin = "Rcpp")
set.seed (1005) # set seed for sampling
x <- sample(1:5L, size = 10, replace = T) #L is Long integer. Keep the nunmber as integer.
x # [1] 1 3 1 3 3 4 1 3 1 2
y <- 3L
y
countf(x,y)
incl <- '
#include<iostream>
#include <algorithm>
#include <vector>
using namespace std;
template <typename S_Type, typename T>
typename iterator_traits<S_Type>::difference_type
S_Type countR(S_Type first, S_Type last, const T & val){
typename iterator_traits<S_Type>::difference_type ret=0;
while (first !=last){
if(*first == val) ++ret;
++first;
}
return ret;
}
'
body_count <- '
#include<iostream>
#include<vector>
#include <algorithm>
using namespace std;
NumericVector xx(x);
int n = xx.size();
NumericVector yy = xx + n;
int val = as<int>(y);
int pos = countR(xx, yy, val);
return wrap(pos);
'
countRcpp3 <- cxxfunction(signature(x = "numeric", y = "numeric"),
body = body_count,
includes = incl,
plugin = "Rcpp")
何か提案をお願いします。または、このタスクで他の論理をお勧めしますか?前もって感謝します。
最初のステップとして、署名付きの関数を抽出できます
int foo(Rcpp::IntegerVector x, int val)
作業コードから。次に、これを一般化して、任意の反復可能な型に作用させることができます。署名:
template <typename T>
int foo(T x, typename std::iterator_traits<typename T::iterator>::value_type val)
ただし、これをRから呼び出すことはできません。Rの関数が異なる型で動作する必要がある場合は、SEXP
引数として使用する必要があります。TYPEOF()
次に、Rデータ型を決定するために使用できます。これを整数ベクトルにまとめると:
#include <Rcpp.h>
template <typename T>
int iter_count(T x, typename std::iterator_traits<typename T::iterator>::value_type val) {
int m = 0;
for(typename T::iterator iter = x.begin(); iter < x.end(); ++iter) {
if(*iter == val) ++m;
}
return m;
}
// [[Rcpp::export]]
int count(SEXP x, SEXP val) {
switch( TYPEOF(x) ) {
case INTSXP: {
return iter_count(Rcpp::as<Rcpp::IntegerVector>(x),
Rcpp::as<Rcpp::IntegerVector>(val)(0));
}
default: {
Rcpp::stop("incompatible SEXP encountered");
}
}
}
/*** R
set.seed (1005)
x <- sample(1:5L, size = 10, replace = T)
y <- 3L
count(x,y)
*/
ここではRcpp属性.cpp
を使用Rcpp::sourceCpp("...")
しています。これをファイルとして保存して使用します。
ところで、あなたのコードでは、これは怪しいように見えます:
NumericVector xx(x);
int n = xx.size();
NumericVector yy = xx + n;
のエンドポイントが必要xx
ですか?次に、xx.end()
またはを使用します。end(xx)
これはではありませんNumericVector
。あなたのコードは、NumericVector
のコンテンツがxx
のサイズによってインクリームされた新しいものを作成しますxx
。ここでは、Rcpp属性を使用した同等のコードを示します。
Rcpp::cppFunction('NumericVector foo(NumericVector xx) {
int n = xx.size();
NumericVector yy = xx + n;
return yy;
}
')
set.seed(42)
foo(runif(3))
# [1] 3.914806 3.937075 3.286140
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加