开始使用免费开始使用

计算行和

发现的第二个瓶颈是计算行和。

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 = ___
)
编辑并运行代码