gpt4 book ai didi

r - 执行标准回收规则

转载 作者:行者123 更新时间:2023-12-03 08:04:15 24 4
gpt4 key购买 nike

R 的一个很好的特性与其固有的矢量化性质有关,是在 An Introduction to R 中描述的回收规则。在第 2.2 节中。

Vectors occurring in the same expression need not all be of the same length. If they are not, the value of the expression is a vector with the same length as the longest vector which occurs in the expression. Shorter vectors in the expression are recycled as often as need be (perhaps fractionally) until they match the length of the longest vector. In particular a constant is simply repeated.



大多数标准函数都使用它,但这样做的代码隐藏在底层 C 代码中。

是否有一种规范的方法可以完全在 R 代码中为函数实现标准回收规则?也就是说,给定一个函数
mock <- function(a, b, c) {
# turn a, b, and c into appropriate recycled versions

# do something with recycled a, b, and c in some appropriately vectorized way
}

哪里 a , b , 和 c是否有可能具有不同长度和未知类型/类别的向量,是否有一种规范的方法来获得一组根据标准回收规则回收的新向量?特别是,我不能假设“做某事”步骤本身会进行适当的回收,所以我需要事先自己做。

最佳答案

我以前用过这个,

expand_args <- function(...){
dots <- list(...)
max_length <- max(sapply(dots, length))
lapply(dots, rep, length.out = max_length)
}

关于r - 执行标准回收规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9335099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com