简体   繁体   English

对数据框或矩阵应用()optimize()?

[英]apply() optimize() on a data frame or matrix?

I have a dataframe, and a cost function that I want to optimize given each row in the data frame. 我有一个数据框和一个成本函数,我希望在数据框中的每一行给出优化。

simplified example: 简化示例:

funct <- function(x,row,y)
{
  r <- row**2 - (x*y)**3
  return(sum(r))

}
apply(dataFr,1,optimize,f=funct,interval=c(0,250),y=4)

funct is the cost function, x is the variable I want to optimize over, and row is an argument that represents a row in a data frame dataFr funct是成本函数,x是我想要优化的变量,而row是表示数据帧dataFr中的行的参数

When I run the above code I get an error 当我运行上面的代码时,我收到一个错误

Error in f(arg, ...) : unused argument (c(4, 8, 23))

What I want to get is a list of x's that optimze the cost, given each row in dataFr 我想得到的是一个x列表,它根据dataFr中的每一行优化了成本

dataFr can be dataFr可以

  X1 X2 X3
1  4  8 23
2  2  4 12
3  3  5 65

this will work: 这将工作:

apply(dataFr,1,function(r) optimize(f=funct,interval=c(0,250),row=r,y=4))

The problem was, as I mentioned in the comments with the row not being used and assigned to the paramter row of the function funct 问题是,正如我在评论中提到的那样,没有使用行并将其分配给函数功能的参数行

By using an anonmous function, naming the current row and assigning it to the row parameter of the function it works 通过使用anonmous函数,命名当前行并将其分配给它工作的函数的row参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM