gpt4 book ai didi

R 循环遍历两个向量

转载 作者:行者123 更新时间:2023-12-03 20:02:29 30 4
gpt4 key购买 nike

再会,
我需要一个为两个参数创建递增 ID 的函数。我想出了这个工作正常的函数,但我希望它被向量化,而且我似乎无法避免 N² 的大 O 因子。有没有“更好”的方法来做到这一点?
标准功能:

threshold <- 3

calculateID <- function(p, r) {
return((p-1) * threshold + r)
}

calculateID(1, 1) #returns 1
calculateID(1, 2) #returns 2
calculateID(1, 3) #returns 3
calculateID(2, 1) #returns 4
#.....
calculateID(5, 3) #returns 15
向量化函数,我想将两个参数作为向量给出,因此该函数只需调用一次:
threshold <- 3
calculateIDVectorized <- function(p, r) {
return(unlist(
lapply(p, function(x) {
lapply(r, function(y) {
(x-1) * threshold + y
})
})
))
}

calculateIDVectorized(c(1, 2, 3, 4, 5), c(1, 2, 3)) # should return 1-15
澄清:我希望使用每个 p 和 r 参数,因此您应该始终得到 length(p * r) 的结果

最佳答案

您可以使用 outer :

calculateIDVectorized <- function(p, r) as.vector(t(outer(p, r, calculateID)))

calculateIDVectorized(c(1, 2, 3, 4, 5), c(1, 2, 3))
#> [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

关于R 循环遍历两个向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65181317/

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