How can I access the levels of the factors of a data.frame in Rcpp when it is passed as an argument from R?

◇◆丶佛笑我妖孽 提交于 2019-12-10 18:52:10

问题


I have the following data.frame df1 with factor fac1 that I have created in R and I pass it as an argument in a Rcpp function. The requested task is to get all the factor levels inside an Rcpp function and use them.

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)

回答1:


After some research I found a solution and I am sharing it.
The Rf_isFactor checks if a data.frame column is a factor or not.
The levels attribute of corresponding IntegerVector (tempVec) returns the factor levels.

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"


来源:https://stackoverflow.com/questions/46323398/how-can-i-access-the-levels-of-the-factors-of-a-data-frame-in-rcpp-when-it-is-pa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!