找到两个向量的平均平均配对 [英] Finding the average mean pairing of two vector

查看:28
本文介绍了找到两个向量的平均平均配对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数变量 res ,它存储从一个向量到另一个向量的每个元素的总和,其中的结果被跟踪.其中 length(a) = 10length(b) = 10 或 15 或任何长度 >长度(a).

I have an integer variable res which stores the sum of of each element from one vector to another vector where the results are kept track. Where length(a) = 10 and length(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 的对都被省略.重复这个过程,直到没有唯一的对.

How can I find the maximum of each unique pair? Let say a10 + b15 = 25 is the maximum, then in the second iteration, any pair containing a10 or b15 are omitted. This process is repeated until no unique pairs are left.

如何修改下面函数中的 if 语句以找到最大唯一配对的平均值?还是有其他方法?

How can I modify the if statement in the below function to find the mean of the maximum unique pairing? Or there is another way round?

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)))

 }

注意:这个问题是我之前的问题.

推荐答案

我们可以把功能改成

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

这篇关于找到两个向量的平均平均配对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆