Apply () optimize () on dataframe or matrix?

I have a dataframe and a cost function that I want to optimize given every row in the dataframe.

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 that I want to optimize, and row is the argument representing the row in the dataFr dataframe

When I run the above code, I get the error

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

      

What I want to get is a list x that optimizes the cost given each row in dataFr

dataFr can be

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

      

+3


source to share


1 answer


this will work:

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

      



The problem was that, as I mentioned in the comments, the string is not used and is assigned to the parameter string of the funct function

Using an anonymous function, naming the current line and assigning it to the string parameter of the function it is working with

+1


source







All Articles