gpt4 book ai didi

r - 在 R 中不使用循环对元素求和

转载 作者:行者123 更新时间:2023-12-02 08:09:45 24 4
gpt4 key购买 nike

假设我有数字字符串

str1 <- c(1, 2, 3) , str2 <- c(4, 7, 10, 18, 20)

和一组数据hex_np <- c(2, 4, 6, 8, 10)

我想显示str1[a] * hex_np + str2[b]中的每个在哪里 a=1,2,3b=1,2,3,4,5

也就是说,

str1[1] * hex_np + str2[1] , str1[1] * hex_np + str2[2] , ..., str1[1] * hex_np + str2[5] , str1[2] * hex_np + str2[1] str1[2] * hex_np + str2[2] , ..., str1[2] * hex_np + str2[5] , str1[3] * hex_np + str2[1] , str1[3] * hex_np + str2[2] , ..., str1[3] * hex_np + str2[5]

在不使用循环的情况下我应该如何做到这一点?

最佳答案

使用expand.grid获取str1str2的所有组合,然后循环遍历行并使用您的公式:

myResult <- apply(expand.grid(str1, str2), 1, function(i)
i[1] * hex_np + i[2])

class(myResult)
# [1] "matrix"

myResult
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
# [1,] 6 8 10 9 11 13 12 14 16 20 22 24 22 24 26
# [2,] 8 12 16 11 15 19 14 18 22 22 26 30 24 28 32
# [3,] 10 16 22 13 19 25 16 22 28 24 30 36 26 32 38
# [4,] 12 20 28 15 23 31 18 26 34 26 34 42 28 36 44
# [5,] 14 24 34 17 27 37 20 30 40 28 38 48 30 40 50

或者我们可以使用maply:

ab <- expand.grid(str1, str2)
myResult2 <- mapply(function(a, b){a * hex_np + b}, ab[, 1], ab[, 2])
identical(myResult, myResult2)
# [1] TRUE

编辑:如果我们想要 3 路组合,请参见下文:

myResult3 <- data.frame(expand.grid(str1, hex_np, str2))
colnames(myResult3) <- c("str1", "hex_np", "str2")

myResult3$res <- with(myResult3, str1 * hex_np + str2)

head(myResult3)
# str1 hex_np str2 res
# 1 1 2 4 6
# 2 2 2 4 8
# 3 3 2 4 10
# 4 1 4 4 8
# 5 2 4 4 12
# 6 3 4 4 16

关于r - 在 R 中不使用循环对元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48360773/

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