求两个向量的平均最大配对 [英] Finding the average maximum pairing of two vector

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

问题描述

我有一个整数变量res,它存储每个元素从一个向量到另一个向量的总和,并保持结果跟踪.

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.

a <- 1:3
b <- 4:6
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 

如何找到每个唯一对的最大值?假设a3 + b3 = 9是最大值,然后在第二次迭代中,任何包含a3b3的对都将被省略,而我们剩下:

How can I find the maximum of each unique pair? Let say a3 + b3 = 9 is the maximum, then in the second iteration, any pair containing a3 or b3 are omitted and we are left with:

res 
#   a1 + b1 a2 + b1 a1 + b2 a2 + b2 
#      5       6         6       7       

下一个最大值是a2 + b2 = 7,然后在上一次迭代中,任何具有a2b2的对都将被省略,而我们剩下:

The next maximum is a2 + b2 = 7, then in the last iteration, any pair with a2 or b2 are omitted and we are left with:

res 
#   a1 + b1  
#      5  

然后我们可以平均最大配对数,即(9+7+5)/3 = 3

Then we can average the maximum pairing i.e. (9+7+5)/3 = 3

我该如何实现?

推荐答案

我们可以使用repeat创建一个函数,以分配从移除具有最大值的元素得到的输出(通过grep输入命名的名称向量,将其作为原始向量的子集),直到其length为1

We can create a function with repeat to assign the output dervied from removing the elements have the maximum value (by greping the names of the named vector to subset the original vector) until it reaches a length of 1

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

 }

f1(res)
#[[1]]
# a1 + b1 
#   5 

#[[2]]
#[1] 7

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

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