找到两个向量

时间:2017-05-02 12:09:11

标签: r vector sum

我有一个整数变量res,它存储从一个向量到另一个向量的每个元素的总和,其中结果保持跟踪。 length(a) = 10length(b) = 10 or 15 or any length > length(a).

的位置
a <- 1:10
b <- 1:15
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   a4+b1   a5+b1 ... a6+b15  a7+b15  a8+b15  a9+b15 a10+b15
#    2       3       4       5       6     ... 21      22      23      24      25 

如何找到每个唯一对的最大值?假设a10 + b15 = 25是最大值,然后在第二次迭代中,省略包含a10b15的任何对。重复该过程直到没有剩下唯一的对。

如何修改以下函数中的if语句以查找最大唯一配对的平均值?还是有另一种方式?

f1 <- function(x) {
  x1 <- max(x)
 repeat {
  x <- x[!grepl(sub(" \\+ ", "|", names(which.max(x))), names(x))]
  x1 <- c(x1, max(x))
  if(length(x)==1) break
   }
  return(list(x, mean(x1)))

 }

注意:此问题是我之前question的后续问题。

1 个答案:

答案 0 :(得分:1)

我们可以将功能更改为

f2 <- function(x) {
   x1 <- max(x)
   repeat {
   i1 <- grepl(sub(" \\+ ", "|", names(which.max(x))), names(x))
 if(all(i1)) break
  x  <-  x[!i1]
  x1 <- c(x1, max(x))

}

return(list(x, mean(x1)))
}

f2(res)
#[[1]]
#a1 + b1 a1 + b2 a1 + b3 a1 + b4 a1 + b5 a1 + b6 
#      2       3       4       5       6       7 

#[[2]]
#[1] 16
相关问题