我有以下data.frame df1 ,我在R中创建了因子 fac1 ,我将它作为参数传递给Rcpp函数。请求的任务是获取Rcpp函数中的所有因子级别并使用它们。
fac1 <- factor(x = sample(x = 1:5,size = 100,replace = T),labels = paste0("D",1:5))
var1 <- sample(x = 1:20,size = 100,replace = T)
fac2 <- factor(x = sample(x = 1:12,size = 100,replace = T),labels = paste0("M",1:12))
df1 <- data.frame(fac1,var1,fac2)
答案 0 :(得分:4)
经过一番研究后,我找到了一个解决方案,我正在分享它 Rf_isFactor 检查data.frame列是否是一个因素 相应 IntegerVector (tempVec)的级别属性返回因子级别。
cppFunction("void GetFactorLevels(DataFrame df1){
CharacterVector varNames = df1.names();
for(int i=0; i<df1.length();i++) {
if(Rf_isFactor(df1[i])==1){
IntegerVector tempVec=df1[i];
CharacterVector factorLevels =tempVec.attr(\"levels\");
Rcout<<varNames[i]<<\": \"<<factorLevels<<std::endl;
}
}
}")
> GetFactorLevels(df1)
fac1: "D1" "D2" "D3" "D4" "D5"
fac2: "M1" "M2" "M3" "M4" "M5" "M6" "M7" "M8" "M9" "M10" "M11" "M12"