R “访问”;“自然胁迫”;来自C/C+的逻辑+;代码

R “访问”;“自然胁迫”;来自C/C+的逻辑+;代码,r,type-conversion,rcpp,coercion,type-coercion,R,Type Conversion,Rcpp,Coercion,Type Coercion,调用unlist或c时,类型将升级为能够表示所有内容的最小类型: > c(as.integer(1), 2.3, '3') [1] "1" "2.3" "3" > c(TRUE, 5) [1] 1 5 > unlist(list(as.integer(1:5), as.complex(2:4))) [1] 1+0i 2+0i 3+0i 4+0i 5+0i 2+0i 3+0i 4+0i 如何从C/C++代码访问此逻辑 我已经查找了C和unlist的C源代码,并在do_C

调用
unlist
c
时,类型将升级为能够表示所有内容的最小类型:

> c(as.integer(1), 2.3, '3')
[1] "1"   "2.3" "3"  
> c(TRUE, 5)
[1] 1 5
> unlist(list(as.integer(1:5), as.complex(2:4)))
[1] 1+0i 2+0i 3+0i 4+0i 5+0i 2+0i 3+0i 4+0i
如何从C/C++代码访问此逻辑

我已经查找了
C
unlist
的C源代码,并在
do_C_dflt
do_unlist
()中找到了以下代码:

变量
data
,类型为
BindData
,由一个似乎定义强制逻辑的例程
AnswerType
计算。但是,类型
BindData
仅在
bind.c
中声明

那么:R的通用强制逻辑是导出到任何地方,还是我必须从
bind.c
复制粘贴代码?(很抱歉这个双关语…

Kevin刚刚发布了一篇文章,这篇文章的精神非常接近,它使用R的API中的宏进行了显式测试:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List do_stuff( List x_ ) {
    List x = clone(x_);
    for( List::iterator it = x.begin(); it != x.end(); ++it ) {
        switch( TYPEOF(*it) ) {
            case REALSXP: {
                NumericVector tmp = as<NumericVector>(*it);
                tmp = tmp * 2;
                break;    
            }
            case INTSXP: {
                if( Rf_isFactor(*it) ) break; // factors have type INTSXP too
                IntegerVector tmp = as<IntegerVector>(*it);
                tmp = tmp + 1;
                break;
            }
            default: {
                stop("incompatible SEXP encountered;");
            }
       }
  }  
  return x;
}
#包括
使用名称空间Rcpp;
//[[Rcpp::导出]]
列出要做的事情(列出x){
列表x=克隆(x_u3;);
for(List::iterator it=x.begin();it!=x.end();++it){
开关(类型(*it)){
案例REALSXP:{
数值向量tmp=as(*it);
tmp=tmp*2;
打破
}
案例INTSXP:{
if(Rf_isFactor(*it))break;//因子的类型也为INTSXP
积分器tmp=as(*it);
tmp=tmp+1;
打破
}
默认值:{
停止(“遇到不兼容的SEXP;”;
}
}
}  
返回x;
}
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List do_stuff( List x_ ) {
    List x = clone(x_);
    for( List::iterator it = x.begin(); it != x.end(); ++it ) {
        switch( TYPEOF(*it) ) {
            case REALSXP: {
                NumericVector tmp = as<NumericVector>(*it);
                tmp = tmp * 2;
                break;    
            }
            case INTSXP: {
                if( Rf_isFactor(*it) ) break; // factors have type INTSXP too
                IntegerVector tmp = as<IntegerVector>(*it);
                tmp = tmp + 1;
                break;
            }
            default: {
                stop("incompatible SEXP encountered;");
            }
       }
  }  
  return x;
}