計算列總和
找出的第二個瓶頸是計算每一列的總和。
total <- apply(d, 1, sum)
在前一個練習中,你把底層物件換成了矩陣。這讓上面的 apply 操作快了 3 倍。
不過你還能再最佳化一步:把 apply() 換成 rowSums()。
本練習屬於課程
撰寫高效 R 程式碼
練習說明
- 使用
rowSums()完成r_sum()函式。 - 使用
microbenchmark()來比較app()與r_sum()的執行時間。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Example data
rolls
# Define the previous solution
app <- function(x) {
apply(x, 1, sum)
}
# Define the new solution
r_sum <- function(x) {
___(x)
}
# Compare the methods
microbenchmark(
app_sol = app(rolls),
r_sum_sol = ___
)