提升R语言使用效率
25 Sep 2016
Go back摘自一篇博客:提升R语言运算效率的11个实用方法,但是原文有些问题,现改进了一下!而且我将最后的一个方法去掉了。
http://m.blog.csdn.net/article/details?id=52190860
引言:
众所周知,当我们利用R语言处理大型数据集时,for循环语句的运算效率非常低。有许多种方法可以提升你的代码运算效率,但或许你更想了解运算效率能得到多大的提升。本文将介绍几种适用于大数据领域的方法,包括简单的逻辑调整设计、并行处理和Rcpp的运用,利用这些方法你可以轻松地处理1亿行以上的数据集。
具体的实际需求:
提出以下问题:
# 下面的代码输出原始数据框:
# Create the data frame
col1 <- runif (12^4, 0, 2)
col2 <- rnorm (12^4, 0, 2)
col3 <- rpois (12^4, 3)
col4 <- rchisq (12^4, 2)
df <- data.frame (col1, col2, col3, col4)
rm(list = ls(pattern = "^col"))
# 逐行判断该数据框(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
}
}
}
)
用户 系统 流逝
6.22 0.02 6.27
循环运算前,记得预先设置好数据结构和输出变量的长度和类型,千万别在循环过程中渐进性地增加数据长度。接下来,我们将探究向量化处理是如何提高处理数据的运算速度。
# after vectorization and pre-allocation
output <- character (nrow(df)) # initialize output vector
df<-df[,-5]
system.time({
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"
} else {
output[i] <- "lesser_than_4"
}
}
df$output<-output})
用户 系统 流逝
1.92 0.00 1.92
将条件判断语句移至循环外可以提升代码的运算速度,接下来本文将利用包含100,000行数据至1,000,000行数据的数据集进行测试:
df<-df[,-5]
# 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
system.time({
for (i in 1:nrow(df)) {
if (condition[i]) {
output[i] <- "greater_than_4"
} else {
output[i] <- "lesser_than_4"
}
}
df$output <- output
})
用户 系统 流逝
0.05 0.00 0.05
另一种优化方法是预先将输出变量赋值为条件语句不满足时的取值,然后只在条件语句为真时执行循环过程。此时,运算速度的提升程度取决于条件状态中真值的比例。
本部分的测试将和case(2)部分进行比较,和预想的结果一致,该方法确实提升了运算效率。
df<-df[,-5]
output <- c(rep("lesser_than_4", nrow(df)))
condition <- (df$col1 + df$col2 + df$col3 + df$col4) > 4
system.time({
for (i in (1:nrow(df))[condition]) { # run loop only for true conditions
if (condition[i]) {
output[i] <- "greater_than_4"
}
}
df$output <- output
})
用户 系统 流逝
0.05 0.00 0.05
利用ifelse()语句可以使你的代码更加简便。ifelse()的句法格式类似于if()函数,但其运算速度却有了巨大的提升。即使是在没有预设数据结构且没有简化条件语句的情况下,其运算效率仍高于上述的两种方法。
df<-df[,-5]
system.time({
output <- ifelse ((df$col1 + df$col2 + df$col3 + df$col4) > 4, "greater_than_4", "lesser_than_4")
df$output <- output
})
用户 系统 流逝
0.02 0.00 0.02
利用which()语句来筛选数据集,我们可以达到Rcpp三分之一的运算速率。
df<-df[,-5]
# Thanks to Gabe Becker
system.time({
want = which(colSums(df) > 4)
output = rep("less than 4", times = nrow(df))
output[want] = "greater than 4"
df$output <- output
})
用户 系统 流逝
0 0 0
df<-df[,-5]
# apply family
system.time({
myfunc <- function(x) {
if ((x['col1'] + x['col2'] + x['col3'] + x['col4']) > 4) {
"greater_than_4"
} else {
"lesser_than_4"
}
}
output <- apply(df[, c(1:4)], 1, FUN=myfunc) # apply 'myfunc' on every row
df$output <- output
})
用户 系统 流逝
0.17 0.00 0.17
这可能不是说明字节码编译有效性的最好例子,但是对于更复杂的函数而言,字节码编译将会表现地十分优异,因此我们应当了解下该函数。
df<-df[,-5]
# byte code compilation
library(compiler)
myFuncCmp <- cmpfun(myfunc)
system.time({
output <- apply(df[, c (1:4)], 1, FUN=myFuncCmp)
df$output <- output
})
用户 系统 流逝
0.12 0.00 0.12
截至目前,我们已经测试了好几种提升运算效率的方法,其中最佳的方法是利用which和ifelse()函数。如果我们将数据量增大十倍,运算效率将会变成啥样的呢?接下来我们将利用Rcpp来实现该运算过程,并将其与ifelse()进行比较。
df<-df[,-5]
library(Rcpp)
setwd("G:/数据分析课程/提升R语言使用效率")
sourceCpp("MyFunc.cpp")
system.time (output <- myFunc(df)) # see Rcpp function below
用户 系统 流逝
0 0 0
下面是利用C++语言编写的函数代码,将其保存为“MyFunc.cpp”并利用sourceCpp进行调用。速度实在快!
// Source for MyFunc.cpp
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
CharacterVector myFunc(DataFrame x) {
NumericVector col1 = x["col1"];
NumericVector col2 = x["col2"];
NumericVector col3 = x["col3"];
NumericVector col4 = x["col4"];
int n = col1.size();
CharacterVector out(n);
for (int i=0; i<n;i++){
if(col1[i]+col2[i]+col3[i]+col4[i]>4){
out[i] = "greater_than_4";
} else {
out[i] = "lesser_than_4";
}
}
return out;
}
这个我下次再研究
RT,向量化比较快但是是以消耗空间为代价的。尽量移除变量并恢复内存容量
可以看到,运算速度比较快的是1)利用which、2)利用ifelse 和 利用Rcpp
下面我们观察一下将df的行数继续增大看看结果会怎么样!
# Create the data frame
col1 <- runif (12^6, 0, 2)
col2 <- rnorm (12^6, 0, 2)
col3 <- rpois (12^6, 3)
col4 <- rchisq (12^6, 2)
df <- data.frame (col1, col2, col3, col4)
rm(list = ls(pattern = "^col"))
#利用which
df<-df[,-5]
system.time({
want = which(colSums(df) > 4)
output = rep("less than 4", times = nrow(df))
output[want] = "greater than 4"
df$output <- output
})
#利用ifelse
df<-df[,-5]
system.time({
output <- ifelse ((df$col1 + df$col2 + df$col3 + df$col4) > 4, "greater_than_4", "lesser_than_4")
df$output <- output
})
#Rcpp
df<-df[,-5]
library(Rcpp)
setwd("G:/数据分析课程/提升R语言使用效率")
sourceCpp("MyFunc.cpp")
system.time (output <- myFunc(df))
which
用户 系统 流逝
0.09 0.05 0.14
ifelse
用户 系统 流逝
1.83 0.07 1.91
Rcpp
用户 系统 流逝
0.24 0.00 0.23
可以看到which 竟然会这么快!