2017-04-06 67 views
1

我有一個很長的數據幀(數百萬行,幾列)。爲了運行固定效應迴歸,我想使用factor函數將分類變量聲明爲因子,但這非常緩慢。我正在尋找一種可以加快速度的潛在解決方案。R因子函數運行緩慢,數據幀長

我的代碼如下:

library(lfe) 
my_data=read.csv("path_to//data.csv") 
attach(data.frame(my_data)) 

和下面是非常慢行:

my_data$col <- factor(my_data$col) 

回答

3

如果你知道你正在創建的因子的水平,這樣可以加快事情相當多。觀察:

library(microbenchmark) 
set.seed(237) 
test <- sample(letters, 10^7, replace = TRUE) 
microbenchmark(noLevels = factor(test), withLevels = factor(test, levels = letters), times = 20) 
Unit: milliseconds 
     expr  min  lq  mean median  uq  max neval cld 
    noLevels 523.6078 545.3156 653.4833 696.4768 715.9026 862.2155 20 b 
withLevels 248.6904 270.3233 325.0762 291.6915 345.7774 534.2473 20 a 

而要獲得OP的情況的水平,我們只需撥打unique

myLevels <- unique(my_data$col) 
my_data$col <- factor(my_data$col, levels = myLevels) 

還有一個Rcpp發行由凱文Ushley(Fast factor generation with Rcpp)編寫的。我修改了一些代碼,假設一個人會知道先驗的情況。引用網站的功能爲RcppNoLevs,修改的Rcpp功能爲RcppWithLevs

microbenchmark(noLevels = factor(test), 
       withLevels = factor(test, levels = letters), 
       RcppNoLevs = fast_factor(test), 
       RcppWithLevs = fast_factor_Levs(test, letters), times = 20) 
Unit: milliseconds 
     expr  min  lq  mean median  uq  max neval cld 
    noLevels 571.5482 609.6640 672.1249 645.4434 704.4402 1032.7595 20 d 
    withLevels 275.0570 294.5768 318.7556 309.2982 342.8374 383.8741 20 c 
    RcppNoLevs 189.5656 203.3362 213.2624 206.9281 215.6863 292.8997 20 b 
RcppWithLevs 105.7902 111.8863 120.0000 117.9411 122.8043 173.8130 20 a 

這裏是假設一個經過所述水平作爲參數修改的RCPP功能:

#include <Rcpp.h> 
using namespace Rcpp; 

template <int RTYPE> 
IntegerVector fast_factor_template_Levs(const Vector<RTYPE>& x, const Vector<RTYPE>& levs) { 
    IntegerVector out = match(x, levs); 
    out.attr("levels") = as<CharacterVector>(levs); 
    out.attr("class") = "factor"; 
    return out; 
} 

// [[Rcpp::export]] 
SEXP fast_factor_Levs(SEXP x, SEXP levs) { 
    switch(TYPEOF(x)) { 
    case INTSXP: return fast_factor_template_Levs<INTSXP>(x, levs); 
    case REALSXP: return fast_factor_template_Levs<REALSXP>(x, levs); 
    case STRSXP: return fast_factor_template_Levs<STRSXP>(x, levs); 
    } 
    return R_NilValue; 
}