令我感到惊讶的是:让我们比较两种获取class变量的方法,这些方法包含许多列的大数据框中的变量: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 )
)
Run Code Online (Sandbox Code Playgroud)
在我的机器上给了我
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
Run Code Online (Sandbox Code Playgroud)
有趣的是,如果我们转换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 ) )
Run Code Online (Sandbox Code Playgroud)
给我
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
Run Code Online (Sandbox Code Playgroud)
为什么这些操作,特别是sapply与a data.frame相比需要更长时间list?还有更惯用的解决方案吗?
Aru*_*run 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
Run Code Online (Sandbox Code Playgroud)
做一个Rprofon 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
Run Code Online (Sandbox Code Playgroud)
您可以通过不要求来加速操作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
Run Code Online (Sandbox Code Playgroud)
区别t3在于您创建一个长度为1000的列表,每个长度为1.而在t1中,它的长度为1000的列表,每个长度为10000.