【问题标题】:Keeping track of the sum of each element of a vector to another vector跟踪一个向量的每个元素与另一个向量的总和
【发布时间】:2017-09-27 22:22:48
【问题描述】:

我有两个向量,我想将向量a 的每个元素与向量b 相加。但我还想跟踪a 和b 的哪个元素会给我这个价值。我尝试了以下方法来获得我的输出:

a <- 1:3
b <- 4:6

store <- list()

for(i in 1:length(b)){
        for(j in 1:length(a)){
                total <- b[i] + a[j]
                store[[paste0("a",i, "+","b",j)]] <- total  
        }        
}

## output
> unlist(store)
## a1+b1 a1+b2 a1+b3 a2+b1 a2+b2 a2+b3 a3+b1 a3+b2 a3+b3 
## 5     6     7     6     7     8     7     8     9 

但我发现使用嵌套的for 循环不灵活,因为如果a 和b 的长度不同,它就不会那么好用。

我遇到了outer() 函数,我可以在其中使用一行代码轻松实现与上述相同的结果:

c(outer(a,b,`+`))
##[1] 5 6 7 6 7 8 7 8 9 

但是,我找不到能给我这个值的一对。

如何在不使用循环的情况下跟踪配对?

【问题讨论】:

  • 你可以试试nm &lt;- outer(seq_along(a), seq_along(b), FUN = function(x, y) sprintf('a%d + b%d', x, y)) 并将其设置为之前outer 输出的名称
  • 完美,非常感谢 akrun!

标签: r vector sum


【解决方案1】:

我们可以使用第二个outer 来获取names 并使用它来分配第一个的名称

nm <- outer(seq_along(a), seq_along(b), FUN = function(x, y) sprintf('a%d + b%d', x, y))
res <- setNames(c(outer(a,b,`+`)), nm)
res 
#   a1 + b1 a2 + b1 a3 + b1 a1 + b2 a2 + b2 a3 + b2 a1 + b3 a2 + b3 a3 + b3 
#      5       6       7       6       7       8       7       8       9 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多