如何获得从R中的函数中吐出最小/最大值的坐标?

问题描述:

如何获取从函数中吐出最小/最大值的坐标?如何获得从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) 
} 

我的坐标是:

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) 

我试着用 “的” 功能是这样的:

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

,但我不知道关于使用哪个函数的语法,我想存储将函数的最小值赋给变量c的坐标alla“min”。 任何帮助将不胜感激。

+0

将函数应用于所有点:'result = sapply(points,myfunct)'。然后'min_point = points [[which.min(result)]]'。 – Gregor

+0

@格雷戈谢谢,但你能告诉我为什么你把双方括号而不是一个? – kys92

+1

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

评论回答,这样可以解决。

使用sapply给你的函数应用到你的列表中的每个项目:

result = sapply(points, myfunct) 

然后使用which.minwhich.max获得最小和最大成绩的指标。示例:

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