天天看點

提升R語言運算效率的11個實用方法

衆所周知,當我們利用R語言處理大型資料集時,for循環語句的運算效率非常低。有許多種方法可以提升你的代碼運算效率,但或許你更想了解運算效率能得到多大的提升。本文将介紹幾種适用于大資料領域的方法,包括簡單的邏輯調整設計、并行處理和Rcpp的運用,利用這些方法你可以輕松地處理1億行以上的資料集。

讓我們嘗試提升往資料框中添加一個新變量過程(該過程中包含循環和判斷語句)的運算效率。下面的代碼輸出原始資料框:

# Create the data frame

col1 <- runif (12^5, 0, 2)

col2 <- rnorm (12^5, 0, 2)

col3 <- rpois (12^5, 3)

col4 <- rchisq (12^5, 2)

df <- data.frame (col1, col2, col3, col4)

逐行判斷該資料框(df)的總和是否大于4,如果該條件滿足,則對應的新變量數值為’greaterthan4’,否則指派為’lesserthan4’。

# Original R code: Before vectorization and pre-allocation

system.time({

for (i in 1:nrow(df)) { # for every row

if ((df[i, 'col1'] + df[i, 'col2'] + df[i, 'col3'] + df[i, 'col4']) > 4) { # check if > 4

df[i, 5] <- "greater_than_4" # assign 5th column

} else {

df[i, 5] <- "lesser_than_4" # assign 5th column

}

})

本文中所有的計算都在配置了2.6Ghz處理器和8GB記憶體的MAC OS X中運作。

1.向量化處理和預設資料庫結構

循環運算前,記得預先設定好資料結構和輸出變量的長度和類型,千萬别在循環過程中漸進性地增加資料長度。接下來,我們将探究向量化處理是如何提高處理資料的運算速度。

# after vectorization and pre-allocation

output <- character (nrow(df)) # initialize output vector

for (i in 1:nrow(df)) {

if ((df[i, 'col1'] + df[i, 'col2'] + df[i, 'col3'] + df[i, 'col4']) > 4) {

output[i] <- "greater_than_4"

output[i] <- "lesser_than_4"

df$output})

2.将條件語句的判斷條件移至循環外

将條件判斷語句移至循環外可以提升代碼的運算速度,接下來本文将利用包含100,000行資料至1,000,000行資料的資料集進行測試:

# after vectorization and pre-allocation, taking the condition checking outside the loop.

output <- character (nrow(df))

condition <- (df$col1 + df$col2 + df$col3 + df$col4) > 4  # condition check outside the loop

if (condition[i]) {

df$output <- output

3.隻在條件語句為真時執行循環過程

另一種優化方法是預先将輸出變量指派為條件語句不滿足時的取值,然後隻在條件語句為真時執行循環過程。此時,運算速度的提升程度取決于條件狀态中真值的比例。

本部分的測試将和case(2)部分進行比較,和預想的結果一緻,該方法确實提升了運算效率。

output <- c(rep("lesser_than_4", nrow(df)))

condition <- (df$col1 + df$col2 + df$col3 + df$col4) > 4

for (i in (1:nrow(df))[condition]) {  # run loop only for true conditions

df$output

4.盡可能地使用 ifelse()語句

利用ifelse()語句可以使你的代碼更加簡便。ifelse()的句法格式類似于if()函數,但其運算速度卻有了巨大的提升。即使是在沒有預設資料結構且沒有簡化條件語句的情況下,其運算效率仍高于上述的兩種方法。

output <- ifelse ((df$col1 + df$col2 + df$col3 + df$col4) > 4, "greater_than_4", "lesser_than_4")

5.使用 which()語句

利用which()語句來篩選資料集,我們可以達到Rcpp三分之一的運算速率。

# Thanks to Gabe Becker

want = which(rowSums(df) > 4)

output = rep("less than 4", times = nrow(df))

output[want] = "greater than 4"

# nrow = 3 Million rows (approx)

user  system elapsed

0.396   0.074   0.481

6.利用apply族函數來替代for循環語句

本部分将利用apply()函數來計算上文所提到的案例,并将其與向量化的循環語句進行對比。該方法的運算效率優于原始方法,但劣于ifelse()和将條件語句置于循環外端的方法。該方法非常有用,但是當你面對複雜的情形時,你需要靈活運用該函數。

# apply family

myfunc <- function(x) {

if ((x['col1'] + x['col2'] + x['col3'] + x['col4']) > 4) {

"greater_than_4"

"lesser_than_4"

output <- apply(df[, c(1:4)], 1, FUN=myfunc)  # apply 'myfunc' on every row

7.利用compiler包中的位元組碼編譯函數cmpfun()

這可能不是說明位元組碼編譯有效性的最好例子,但是對于更複雜的函數而言,位元組碼編譯将會表現地十分優異,是以我們應當了解下該函數。

# byte code compilation

library(compiler)

myFuncCmp <- cmpfun(myfunc)

output <- apply(df[, c (1:4)], 1, FUN=myFuncCmp)

8.利用Rcpp

截至目前,我們已經測試了好幾種提升運算效率的方法,其中最佳的方法是利用ifelse()函數。如果我們将資料量增大十倍,運算效率将會變成啥樣的呢?接下來我們将利用Rcpp來實作該運算過程,并将其與ifelse()進行比較。

library(Rcpp)

sourceCpp("MyFunc.cpp")

system.time (output <- myFunc(df)) # see Rcpp function below

下面是利用C++語言編寫的函數代碼,将其儲存為“MyFunc.cpp”并利用sourceCpp進行調用。

// Source for MyFunc.cpp 

#include 

using namespace Rcpp; 

// [[Rcpp::export]] 

CharacterVector myFunc(DataFrame x) { 

NumericVector col1 = as(x["col1"]); 

NumericVector col2 = as(x["col2"]); 

NumericVector col3 = as(x["col3"]); 

NumericVector col4 = as(x["col4"]); 

int n = col1.size(); 

CharacterVector out(n); 

for (int i=0; i 4){ 

out[i] = "greater_than_4"; 

} else { 

out[i] = "lesser_than_4"; 

return out; 

9.利用并行運算

并行運算的代碼:

# parallel processing

library(foreach)

library(doSNOW)

cl <- makeCluster(4, type="SOCK") # for 4 cores machine

registerDoSNOW (cl)

# parallelization with vectorization

output <- foreach(i = 1:nrow(df), .combine=c) %dopar% {

return("greater_than_4")

return("lesser_than_4")

10.盡早地移除變量并恢複記憶體容量

在進行冗長的循環計算前,盡早地将不需要的變量移除掉。在每次循環疊代運算結束時利用gc()函數恢複記憶體也可以提升運算速率。

11.利用記憶體較小的資料結構

data.table()是一個很好的例子,因為它可以減少資料的記憶體,這有助于加快運算速率。

dt <- data.table(df)  # create the data.table

for (i in 1:nrow (dt)) {

if ((dt[i, col1] + dt[i, col2] + dt[i, col3] + dt[i, col4]) > 4) {

dt[i, col5:="greater_than_4"]  # assign the output as 5th column

dt[i, col5:="lesser_than_4"]  # assign the output as 5th column

總結

方法:速度, nrow(df)/time_taken = n 行每秒

1.原始方法:1X, 856.2255行每秒(正則化為1)

2.向量化方法:738X, 631578行每秒

3.隻考慮真值情況:1002X,857142.9行每秒

4.ifelse:1752X,1500000行每秒

5.which:8806X,7540364行每秒

6.Rcpp:13476X,11538462行每秒