当使用 Rcpp 创建 DataFrame 时,如下所示:
cppFunction('
DataFrame testf(){CharacterVector character = {"B","D"};
return(DataFrame::create(Named("foo")=character));}'
)
Run Code Online (Sandbox Code Playgroud)
生成的 DataFrame 始终将字符向量转换为因子。
df <- testf()
print(class(df$foo))
# > [1] "factor"
Run Code Online (Sandbox Code Playgroud)
有没有办法在 C++ 中防止这种情况发生?R可以直接使用该stringsAsFactors = FALSE选项。
当我第一次看到这个问题时,我认为这肯定是重复的,但经过搜索后我认为不是!当然,这个问题已经在Rcpp-devel中得到解决。我将在这里展示这种方法;stringsAsFactors向 中添加一个命名元素集false,类似于 R:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
DataFrame testf(){
CharacterVector character = {"B","D"};
return(DataFrame::create(Named("foo")=character,
Named("stringsAsFactors") = false));
}
Run Code Online (Sandbox Code Playgroud)
然后在行动中:
Rcpp::sourceCpp("so.cpp")
options(stringsAsFactors = TRUE)
df <- testf()
print(class(df$foo))
# [1] "character"
Run Code Online (Sandbox Code Playgroud)
您可能会注意到我明确将默认值设置stringsAsFactors为TRUEvia options()。这是因为从 R 4.0.0(我目前在我的笔记本电脑上运行)开始,默认值不再是TRUE,而是FALSE。