Finding the average maximum pairing of two vector

2019-05-23 22:23发布

问题:

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 

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       

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  

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

How can I achieve this?

回答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


标签: r vector max