1

How do I get the coordinates that spits out min/max value from the function?

my function code is :

myfunct <- function(theta){
for (h in 1:nrow(temp)){
theta_i <- theta[temp[h,1]]              #i-th position
theta_j <- theta[temp[h,2]]              #j-th position
L1 <- -y[temp[h,2],temp[h,1]] * (theta_i - theta_j) + log(1+exp(theta_i - 
theta_j))
}
L2 <- L1 + 0.5 * lambda * norm(theta, "2")^2
return(L2)
}

my coordinates are:

e1 <- c(1,0,0,0,0,0,0,0,0,0)
e2 <- c(0,1,0,0,0,0,0,0,0,0)
e3 <- c(0,0,1,0,0,0,0,0,0,0)
e4 <- c(0,0,0,1,0,0,0,0,0,0)
e5 <- c(0,0,0,0,1,0,0,0,0,0)
e6 <- c(0,0,0,0,0,1,0,0,0,0)
e7 <- c(0,0,0,0,0,0,1,0,0,0)
e8 <- c(0,0,0,0,0,0,0,1,0,0)
e9 <- c(0,0,0,0,0,0,0,0,1,0)
e10 <- c(0,0,0,0,0,0,0,0,0,1)
unitvect <- c(1,1,1,1,1,1,1,1,1,1)

points <- list(e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,unitvect)

I tried with "which" function something like:

for (i in 1:10){
 min <- which(points[[i]] == min(myfunct(points[[i]])
}

but I do not know the syntax on using which function, and I want to store coordinate that gives min value from the function in to variable called "min". Any help will be appreciated.

kys92
  • 73
  • 3
  • 8
  • Apply function to all points: `result = sapply(points, myfunct)`. Then `min_point = points[[which.min(result)]]`. – Gregor Thomas Oct 20 '17 at 15:10
  • @Gregor thanks, but could you please tell me why you put double square brackets instead of one? – kys92 Oct 20 '17 at 15:21
  • 1
    https://stackoverflow.com/questions/1169456/the-difference-between-and-notations-for-accessing-the-elements-of-a-lis – Jake Kaupp Oct 20 '17 at 15:24

1 Answers1

0

Comment to answer so this can be resolved.

Use sapply to apply your function to each item of your list:

result = sapply(points, myfunct)

Then use which.min and which.max to get the index of the min and max results. Example:

min_point = points[[which.min(result)]]
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294