by
函数是否创建了一次增长一个元素的列表?
我需要处理一个数据框,其中大约有4M个观测值按因子列分组。情况类似于以下示例:
> # Make 4M rows of data
> x = data.frame(col1=1:4000000, col2=10000001:14000000)
> # Make a factor
> x[,"f"] = x[,"col1"] - x[,"col1"] %% 5
>
> head(x)
col1 col2 f
1 1 10000001 0
2 2 10000002 0
3 3 10000003 0
4 4 10000004 0
5 5 10000005 5
6 6 10000006 5
现在,其中一列上的tapply
需要一段合理的时间:
> t1 = Sys.time()
> z = tapply(x[, 1], x[, "f"], mean)
> Sys.time() - t1
Time difference of 22.14491 secs
但如果我这样做:
z = by(x[, 1], x[, "f"], mean)
那几乎没有在同一时间完成(我在一分钟后放弃了)。
当然,在上面的示例中,可以使用tapply
,但实际上我需要一起处理多个列。有什么更好的方法呢?
答案 0 :(得分:4)
by
比tapply
慢,因为它正在包裹by
。
我们来看一些基准测试:tapply
在这种情况下比使用by
更新以包含@ Roland的精彩推荐:
library(rbenchmark)
library(data.table)
dt <- data.table(x,key="f")
using.tapply <- quote(tapply(x[, 1], x[, "f"], mean))
using.by <- quote(by(x[, 1], x[, "f"], mean))
using.dtable <- quote(dt[,mean(col1),by=key(dt)])
times <- benchmark(using.tapply, using.dtable, using.by, replications=10, order="relative")
times[,c("test", "elapsed", "relative")]
#------------------------#
# RESULTS #
#------------------------#
# COMPARING tapply VS by #
#-----------------------------------
# test elapsed relative
# 1 using.tapply 2.453 1.000
# 2 using.by 8.889 3.624
# COMPARING data.table VS tapply VS by #
#------------------------------------------#
# test elapsed relative
# 2 using.dtable 0.168 1.000
# 1 using.tapply 2.396 14.262
# 3 using.by 8.566 50.988
虽然,请注意它们相对于非因素输入都有所改善,而data.table仍然大致相同或更差
x[, "f"] <- as.factor(x[, "f"])
dt <- data.table(x,key="f")
times <- benchmark(using.tapply, using.dtable, using.by, replications=10, order="relative")
times[,c("test", "elapsed", "relative")]
# test elapsed relative
# 2 using.dtable 0.175 1.000
# 1 using.tapply 1.803 10.303
# 3 using.by 7.854 44.880
?by
:描述
Function by是一个面向对象的包装器,用于应用于数据帧。
让我们来看看by
(或更具体,by.data.frame
)的来源:
by.data.frame
function (data, INDICES, FUN, ..., simplify = TRUE)
{
if (!is.list(INDICES)) {
IND <- vector("list", 1L)
IND[[1L]] <- INDICES
names(IND) <- deparse(substitute(INDICES))[1L]
}
else IND <- INDICES
FUNx <- function(x) FUN(data[x, , drop = FALSE], ...)
nd <- nrow(data)
ans <- eval(substitute(tapply(seq_len(nd), IND, FUNx, simplify = simplify)),
data)
attr(ans, "call") <- match.call()
class(ans) <- "by"
ans
}
我们立即看到仍有来电tapply
加上许多额外内容(包括对deparse(substitute(.))
和eval(substitute(.))
的调用,两者都相对较慢)。因此,tapply
比by
的类似调用相对更快是有意义的。
答案 1 :(得分:3)
关于更好的方法:使用4M行,您应该使用data.table
。
library(data.table)
dt <- data.table(x,key="f")
dt[,mean(col1),by=key(dt)]
dt[,list(mean1=mean(col1),mean2=mean(col2)),by=key(dt)]
dt[,lapply(.SD,mean),by=key(dt)]