1
5
@duckmayr的回答非常准确,并且显示了一个重要的细节:我们还可以隐藏实现细节 函数后面 因为毕竟这就是全部 Rcpp糖 不管怎样,等人都为我们做了。 但是,如果我们首先将矩阵转换为向量,对该向量进行操作,然后恢复矩阵,那么我们可以依赖于@增超所期望的Sugar操作。这是因为在内部,矩阵只是一个具有附加维度的向量(二阶;数组泛化为两个以上)。
但事实证明。。。这个版本(稍微)比循环更昂贵(而且比处理列稍微便宜)。有关完整的详细信息,请参见下面的功能
但非显而易见的元素
道德的 :简单循环解决方案复制临时对象最少,速度最快。总的来说,三者之间的速度差几乎无关紧要。 对于较大的矩阵 不复制临时文件 变得更重要:
下面是完整代码。
编辑:
我们可以再删除一行相对于
|
2
4
我假设“整洁的方式”是指避免循环,而使用Rcpp中提供的语法糖。因为sugar为向量提供了一个具有一个值的比较器,而不是为矩阵提供了一个值(参见 here 和 here ),我认为目前最“整洁的方式”是(仅)在列(或行)上循环,即不必在列和行上循环:
然而,我建议避免额外的循环并不能真正为您带来可读性方面的任何好处(事实上,可能会损害代码某些读者的可读性);考虑循环行和列的函数:
我真的看不出这怎么会很难输入,它似乎本质上是性能等效的(平均执行时间略低,但中位数略高——请参见下面的基准测试),至少对于一些读者来说,我敢打赌,它会更清楚地显示出你在做什么。 也就是说,如果跳过一个循环对你有帮助,我认为这是目前你能做的最好的事情。
|
Marc B. · 使用ggplot2创建条形图时“缺少值” 1 年前 |
Mallikarjun M · 如何使用随机森林进行时间序列预测? 1 年前 |
ly li · 模型摘要:当表格形状改变时,拟合优度消失 1 年前 |
RoyBatty · 统计每个字符在整个数据集中出现的次数 2 年前 |
stats_noob · R: 记录某个“行为”发生的循环的索引? 2 年前 |