0
$\begingroup$

I need some help getting pointed in the right direction for creating a regression model in R with data that looks like this.

This is my first foray into this. So using Excel's trend line equation as my reference, I was able to create a logarithmic trend line for another set of data which matched between the two applications.

However, with this specific example, I'm not sure how to formulate the model or even if I should be using non-linear vs linear regression with transformation. Below is an example of the data in the plot.

x = c(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
y = c(0.008,0.004,0.0025,0.0024,0.0023,0.0022,0.0021,0.002,0.0018,0.0005,0.012,0.006,
     0.00375,0.0036,0.00345,0.0033,0.00315,0.003,0.0027,0.00075)
z = c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2)

df = data.frame(x, y, z)

plot(df$y ~ df$x, type="p", pch=20, col=df$z)

Sample Data

$\endgroup$
  • $\begingroup$ try lm(y ~ -log(x)) $\endgroup$ – Aksakal Feb 3 '15 at 15:49
  • 3
    $\begingroup$ This looks more like a deterministic sequence than a set of stochastic data. What are these data? $\endgroup$ – gung - Reinstate Monica Feb 3 '15 at 15:49
1
$\begingroup$

Use nls() to fit any curve. It takes a user-defined function as an argument. In your case you have two inflection points, so a cubic might work. You could also define a higher-order polynomial.

rhs <- function(x, b0, b1, b2, b3) {
    return(b0 + b1*x + b2*x^2 + b3*x^3)
}

model <- nls(y ~ rhs(x, intercept, linear, quadratic, cubic), data=df, 
             start=list(intercept=0.015, linear=-.001, quadratic=0, cubic=0.01), trace=T)

If your start values are at all reasonable you will get a good fit.

$\endgroup$
  • $\begingroup$ Thanks. I had experimented with that, but wasn't getting the right result. How would you modify your function to incorporate for Z? Would I add a +b4*z into the function? (Assuming Z shifts the series up linearly). $\endgroup$ – ElPresidente Feb 3 '15 at 16:07
  • 1
    $\begingroup$ Any function you can write will work. You just need to supply arguments from your dataframe. You'll get back the fitted values. See css.cornell.edu/faculty/dgr2/pubs/list.html#pubs_m_R item 11 Rossiter, DG 2005. Technical Note: Fitting rational functions to time series in R. Technical Report ITC, Enschede, NL. Version 1, December 2005. 15 pp. for some ideas, $\endgroup$ – 罗大伟 Feb 3 '15 at 16:25
  • $\begingroup$ Note that a polynom is not non-linear in its parameters. It would be better practice to use lm(y ~ poly(x, degree = 3), data = df). Or possibly lm(y ~ poly(x, degree = 3, raw = TRUE), data = df) $\endgroup$ – Roland Feb 4 '15 at 8:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.