【发布时间】:2020-07-03 04:28:29
【问题描述】:
我创建了这个函数,它接受数字并根据数字是否为素数返回 TRUE 或 FALSE。
is.prime <- function(num) {
if (num == 2) {
TRUE
} else if (any(num %% 2:(num-1) == 0)) {
FALSE
} else {
TRUE
}
}
然而,这个函数只接受一个值,例如这很好用:
> is_prime(17)
[1] TRUE
如果我插入一个向量,我想查看每个元素的 TRUE 或 FALSE。例如,
> is_prime(c(17,5,10,22,109,55))
[1] TRUE
Warning messages:
1: In if (x == 1) { :
the condition has length > 1 and only the first element will be used
2: In 2:(floor(x/2)) :
numerical expression has 6 elements: only the first used
3: In x%%2:(floor(x/2)) :
longer object length is not a multiple of shorter object length
这是针对第一个元素进行评估的,但我想看看
TRUE TRUE FALSE FALSE TRUE FALSE
对于向量
is_prime(c(17,5,10,22,109,55))
如何修改函数以使用相同的算法进行矢量化?
【问题讨论】:
标签: r function vectorization primes