1

I have a dataframe, with

### create sample data
set.seed(1)
x = runif(n = 100, 0, 20)
beta1 = 2
beta2 = 1
beta3 = (1/2)

### Create sample data frame and vector
y = beta1 + beta2*x^(beta3) + rnorm(n = 100, 0, 0.01)
 data = as.data.frame(cbind(y,x))

 ### Fitting the data with nls()-function;
 fit1 = nls(
 y~vb1(x,beta1,beta2,beta3),
 data=data,start=list(beta1 = 0, beta2 = 1, beta3 = 1)
)

where

 vb1 = function(x,beta1,beta2,beta3){
   beta1 + beta2*x^(beta3)
 }

In the end I want to plot the output:

 plot(y~x, col = 3)
 nlsTracePlot(fit1,vb1(x,beta1,beta2,beta3),legend="bottomright")

However, it gives the following error,

 3. stop(gettextf("'%s' is not a function, character or symbol",           deparse(FUN)), domain = NA)
 2. match.fun(fun)
 1. nlsTracePlot(fit1, vb1(x, beta1, beta2, beta3), legend = "bottomright")

Everything works just fine, until I try to plot it with the above function.

5th
  • 2,097
  • 3
  • 22
  • 41
Serkan
  • 1,855
  • 6
  • 20

1 Answers1

1

Assuming you are using the FSA package, you will need to pass the fun argument a raw function. The function needs to be specified in a particular way. See documentation of nlsTracePlot for more information.

vb1 <- function(x, beta1, beta2, beta3){
  if (length(beta1) == 3) {
    beta2 <- beta1[2]
    beta3 <- beta1[3]
    beta1 <- beta1[1]
  }
  beta1 + beta2 * x^(beta3)
}

plot(y ~ x, col = 3)
nlsTracePlot(fit1, vb1, legend = "bottomright")

enter image description here

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
  • This is really interesting! I will give it a try - I highly appreciate your answer. – Serkan Sep 22 '18 at 15:21
  • I implemented your solution, and it worked like a charm. After 3 hours of trying to solve it, its done! Thank you so much! There is a few things that I do not understand, which I would hope you could clarify; Firstly, what is it that the if else function does, that if its omitted, the function fails? Secondly, I count 7 lines, but NLS finished after 6 iterations. What am I missing here? – Serkan Sep 22 '18 at 15:36
  • @Kartal1903 6 + initial iteration with starting parameters is 7 lines, I reckon? – Roman Luštrik Sep 22 '18 at 22:47