rfunctionloopsfor-loopnonlinear-functions

Generating a function via for-loop for the Jacobian matrix in R


Suppose I have the following two variables y and z and the variable x

y = 1:10
z = 1:10

Now I would like to create a jacobian of the following function

f <- function(x)  c(y[1]*x[1]+z[1]*x[2],
                    y[2]*x[1]+z[2]*x[2],
                      :   :     :    :
                    y[10]*x[1]+z[10]*x[2])

Then obtaining the Jacobian can be easily obtained by

jacobian(f, c(1,1))

Now suppose

y= 1:i. 

When i becomes large, computing the function manually becomes a time-consuming task.

Is there a way to construct the same function for i?

I tried the following:

for (i in 1:10) {
  f[i] <- function(x)  c(y[i]*x[1]+z[i]*x[2])
} 

jacobian(f, c(1,1))

ThomasIsCoding suggests:

f <- function(x) tcrossprod(cbind(y, z), t(x))

Which works perfectly for this case.

Now suppose that the function is more complex

y[1]*x[1]^2+z[1]/x[2]

The t(x) suggested does no longer work. How do I now write a vector for x?


Solution

  • You can try the following way for function f

    f <- function(x) tcrossprod(cbind(y, z), t(x))