2017-10-20 3 views
1

함수에서 최소/최대 값으로 튀어 나온 좌표를 얻으려면 어떻게해야합니까?R의 함수에서 최소/최대 값을 뱉어내는 좌표를 얻는 방법?

내 기능의 코드는 다음과 같습니다

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

내 좌표

은 다음과 같습니다

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

하지만 난 몰라 :

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) 

내가 기능 무언가 같이하는 것은 "어떤"로 시도 어떤 함수를 사용하는지에 대한 문법, 그리고 함수의 최소값을 변수 c에주는 좌표를 저장하고 싶습니다. alled "min". 도움이 될 것입니다.

+0

모든 포인트에 기능을 적용하십시오 : 'result = sapply (points, myfunct)'. 그런 다음'min_point = points [[which.min (result)]]'. – Gregor

+0

@ Gregor 감사합니다.하지만 왜 대신에 대괄호를 두 개 넣을 수 있는지 말해 주시겠습니까? – kys92

+1

https://stackoverflow.com/questions/1169456/the-difference-between-and-notations-for-accessing-the-elements-of-a-lis –

답변

0

답변을 드리 자면이 문제를 해결할 수 있습니다.

사용 sapply는 목록의 각 항목에 함수를 적용합니다 :

result = sapply(points, myfunct) 

그런 다음 최소 및 최대 결과의 인덱스를 얻을 which.minwhich.max를 사용합니다. 예 :

min_point = points[[which.min(result)]]