从函数中获取第一个唯一值

时间:2016-04-17 10:57:05

标签: r

这是我的功能:

g <- function(x,y){
   x <- (x-y):x
   y <- 1:30 # ------> (y is always fixed 1:30)
   z<- outer(x,y,fv) # ---->(fv is a previous function)
   s <- colSums(z)
   which(s==max(s),arr.ind=T)
}

它告诉我s中最大值的位置。我在选择y时基本上有一个问题,因为给定一个小y,max(s)在s中出现不止一次。例如:

#given x=53 
> g(53,1)
[1] 13 16 20 22 25 26 27 
> g(53,2)
[1] 20 25 26
> g(53,3)
[1] 20 25 26
> g(53,4)
[1] 20 25 26
> g(53,5)
[1] 20 25
> g(53,6) 
[1] 25   -----> This is the only result i would like from my function (right y=6)

另一个例子:

# given x=71
> g(71,1)
[1] 7 9 14 
> g(71,2)
[1] 7 14
> g(71,3)
[1] 14 -----> my desired result (right y=3)

因此,我希望一个函数能够得到尽可能小的第一个唯一解(ex:g(53)=25 , g(71)=14, ...)。有帮助吗?感谢

这是一个简化的例子。我希望在提问中更清楚:

#The idea is the same:

n <- 1:9
e <- rep(nn,500)
p<- sample(e)   # --->(Need to sample in order to have more max later (mixed matrix)
mat <- matrix(p,90)

g <- function(x,y){
x <- (x-y):x
k <- rowSums(mat[,x])
which(k==max(k), arr.ind=T)
}

#In my sample matrix :

k <- rowSums(mat[,44:45])
which(k==max(k), arr.ind=T)
[1] 44 71 90
#In fact
g(45,1)
[1] 44 71 90  # ---> more than one solution

g(45,2)
[1] 90  # ----> I would like to pick up this value wich is the first unique solution given x=45

因此,我想要一个函数,在给定x的情况下,y的第一个唯一解决方案尽可能小(在这个新的例外:g(45)=90 ...)。

2 个答案:

答案 0 :(得分:1)

我明白了。这有点长,但我认为是对的。

考虑第二个简化示例:

 g <- function(x,y){
 x <- (x-y):x
 k <- rowSums(mat[,x])
 q <- which(k==max(k), arr.ind=T)
 length(q)
 }

 gv <- Vectorize(g)

 l <- function(x){
 y<- 1:30 # <- (until 30 to be sure)
 z<- outer(x,y,gv)
 y <- which.min(z) # <- (min is surely length=1 and which.min takes the first)
 x <- (x-y):x
 k <- rowSums(mat[,x])
 q <- which(k==max(k), arr.ind=T)
 q
 }

 l(45)
 [1] 90

答案 1 :(得分:0)

好像你可以用recursive function来做这件事。请考虑以下事项:

set.seed(42)
n = 1:9
e = rep(n, 500)
p = sample(e)
mat = matrix(p, 90)

g <- function(x, y=1) {
  xv <- (x-y):x
  k <- rowSums(mat[, xv])
  i <- which(k == max(k), arr.ind=T)
  n <- length(i)
  if (n == 1) {
    return(y) # want to know the min y that solves the problem, right?
  } else {
    y <- y + 1 # increase y by 1
    g(x,y)  # run our function again with a new value of y
  }
}

您现在应该能够运行g(45)并获得1作为结果,因为这是解决问题的y的值,而g(33)得到2。