简体   繁体   中英

Interpolation and Curve fitting with R

I am a chemical engineer and very new to R. I am attempting to build a tool in R (and eventually a shiny app) for analysis of phase boundaries. Using a simulation I get output that shows two curves which can be well represented by a 4th order polynomial. The data is as follows:

https://i.stack.imgur.com/8Oa0C.jpg

The procedure I have to follow uses the difference between the two curves to produce a second. In order to compare the curves, the data has to increase as a function of pressure in set increments, for example of 0.2 As can be seen, the data from the simulation is not incremental and there is no way to compare the curves based on the output.

To resolve this, in excel I carried out the following steps on each curve:

  • I plotted the data with pressure on the x axis and temperature on the y axis
  • Found the line of best fit using a 4th order polynomial
  • Used the equation of the curve to calculate the temperature at set increments of pressure

From this, I was able to compare the curves mathematically and produce the required output.

Does anyone have any suggestions how to carry this out in R, or if there is a more statistical or simplified approach that I have missed(extracting bezier curve points etc)?

As a bit of further detail, I have taken the data and merged it using tidyr so that the graphs (4 in total) are displayed in just three columns, the graph title, temperature and pressure. I did this after following a course on ggplot2 on Datacamp, but not sure if this format is suitable when carrying out regression etc? The head of my dataset can be seen here:

https://i.stack.imgur.com/WeaPz.jpg

I am very new to R, so apologies if this is a stupid question and I am using the wrong terms.

Though I agree with @Jaap's comment, polynomial regression is very easy in R. I'll give you the first line:

x <- c(0.26,3.33,5.25,6.54,7.38,8.1,8.73,9.3,9.81,10.28,10.69,11.08,11.43,11.75,12.05,12.33)
y <- c(16.33,24.6,31.98,38.38,43.3,48.18,53.08,57.99,62.92,67.86,72.81,77.77,82.75,87.75,92.77,97.81)
lm <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4))

Now your polynomial coefficients are in lm$coef , you can extract them and easily plot the fitted line, eg:

coefs <- lm$coef
plot(x, y)
lines(x, coefs[1] + coefs[2] * x + coefs[3] * x^2 + coefs[4] * x^3 + coefs[5] * x^4)

The fitted values are also simply given using lm$fit . Build the same polynomial for the second curve and compare the coefficients, not just the "lines".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM