Skip to content

Instantly share code, notes, and snippets.

@aschleg
Created June 24, 2017 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aschleg/62d00ed41dc96b9013dee1b20beee6fb to your computer and use it in GitHub Desktop.
Save aschleg/62d00ed41dc96b9013dee1b20beee6fb to your computer and use it in GitHub Desktop.
R function for performing Lagrangian polynomial interpolation
# Function for performing Lagrangian polynomial interpolation https://en.wikipedia.org/wiki/Lagrange_polynomial.
# Requires the package rSymPy https://cran.r-project.org/web/packages/rSymPy/index.html.
# Parameters:
# x: x values of interpolating points
# y: values corresponding to x values
# Returns:
# Simplified interpolated polynomial that passes through the given x and y points
lagrange.poly <- function(x, y) {
require(rSymPy)
if (length(x) != length(y)) {
stop('x and y must be of equal length')
}
l <- list() # List to store Lagrangian polynomials L_{1,2,3,4}
k <- 1
for (i in x) {
# Set the numerator and denominator of the Lagrangian polynomials to 1 and build them up
num <- 1
denom <- 1
# Remove the current x value from the iterated list
p <- x[! x %in% i]
# For the remaining points, construct the Lagrangian polynomial by successively
# appending each x value
for (j in p) {
num <- paste(num, "*", "(", 'x', " - ", as.character(j), ")", sep = "", collapse = "")
denom <- paste(denom, "*", "(", as.character(i)," - ", as.character(j), ")", sep = "", collapse = "")
}
# Set each Lagrangian polynomial in rSymPy to simplify later.
l[k] <- paste("(", num, ")", "/", "(", denom, ")", sep = "", collapse = "")
k <- k + 1
}
# Similar to before, we construct the final Lagrangian polynomial by successively building
# up the equation by iterating through the polynomials L_{1,2,3,4} and the y values
# corresponding to the x values.
eq <- 0
for (i in 1:length(y)) {
eq <- paste(eq, '+', as.character(y[i]), "*", l[[i]], sep = "", collapse = "")
}
# Define x variable for rSymPy to simplify
x <- Var('x')
# Simplify the result with rSymPy and return the polynomial
return(sympy(paste("simplify(", eq, ")")))
}
@TheAlchemistNerd
Copy link

I have a value of interval censored lifetable data. I would love to use interpolation to fill in the missing values in R.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment