令我感到惊讶的是:让我们比较两种获取class
es for变量的方法,这些方法包含许多列的大数据框:sapply
解决方案和for
循环解决方案
bigDF <- as.data.frame( matrix( 0, nrow=1E5, ncol=1E3 ) )
library( microbenchmark )
for_soln <- function(x) {
out <- character( ncol(x) )
for( i in 1:ncol(x) ) {
out[i] <- class(x[,i])
}
return( out )
}
microbenchmark( times=20,
sapply( bigDF, class ),
for_soln( bigDF )
)
在我的机器上给了我
Unit: milliseconds
expr min lq median uq max
1 for_soln(bigDF) 21.26563 21.58688 26.03969 163.6544 300.6819
2 sapply(bigDF, class) 385.90406 405.04047 444.69212 471.8829 889.6217
有趣的是,如果我们将bigDF
转换为列表,sapply
又一次又好又快。
bigList <- as.list( bigDF )
for_soln2 <- function(x) {
out <- character( length(x) )
for( i in 1:length(x) ) {
out[i] <- class( x[[i]] )
}
return( out )
}
microbenchmark( sapply( bigList, class ), for_soln2( bigList ) )
给了我
Unit: milliseconds
expr min lq median uq max
1 for_soln2(bigList) 1.887353 1.959856 2.010270 2.058968 4.497837
2 sapply(bigList, class) 1.348461 1.386648 1.401706 1.428025 3.825547
与sapply
相比,为什么这些操作(尤其是data.frame
)使用list
的时间要长得多?还有更惯用的解决方案吗?
答案 0 :(得分:13)
edit:
旧提议的解决方案t3 <- sapply(1:ncol(bigDF), function(idx) class(bigDF[,idx]))
现已更改为t3 <- sapply(1:ncol(bigDF), function(idx) class(bigDF[[idx]]))
。它甚至更快。感谢@Wojciech
的评论
我能想到的原因是您正在将data.frame转换为不必要的列表。此外,您的结果也不相同
bigDF <- as.data.frame(matrix(0, nrow=1E5, ncol=1E3))
t1 <- sapply(bigDF, class)
t2 <- for_soln(bigDF)
> head(t1)
V1 V2 V3 V4 V5 V6
"numeric" "numeric" "numeric" "numeric" "numeric" "numeric"
> head(t2)
[1] "numeric" "numeric" "numeric" "numeric" "numeric" "numeric"
> identical(t1, t2)
[1] FALSE
在Rprof
上执行sapply
表示所有花费的时间都在as.list.data.fraame
Rprof()
t1 <- sapply(bigDF, class)
Rprof(NULL)
summaryRprof()
$by.self
self.time self.pct total.time total.pct
"as.list.data.frame" 1.16 100 1.16 100
您可以不要求as.list.data.frame
来加快操作。相反,我们可以直接查询data.frame
的每列的类,如下所示。这与您实际使用for-loop
完成的操作完全相同。
t3 <- sapply(1:ncol(bigDF), function(idx) class(bigDF[[idx]]))
> identical(t2, t3)
[1] TRUE
microbenchmark(times=20,
sapply(bigDF, class),
for_soln(bigDF),
sapply(1:ncol(bigDF), function(idx)
class(bigDF[[idx]]))
)
Unit: milliseconds
expr min lq median uq max
1 for-soln (t2) 38.31545 39.45940 40.48152 43.05400 313.9484
2 sapply-new (t3) 18.51510 18.82293 19.87947 26.10541 261.5233
3 sapply-orig (t1) 952.94612 1075.38915 1159.49464 1204.52747 1484.1522
t3
的区别在于您创建了一个长度为1000的列表,每个长度为1.而在t1中,它是一个长度为1000的列表,每个长度为10000.