Fitting regression in R

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)


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

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,

• 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) – Roland Feb 4 '15 at 8:27