R Linear Interpolation of data into every 1 unit where max(x) is variable and is not a whole number

I have the following two data sets

'''

 Percent <- c(0,30.4,99.6)
 Value1 <- c(100,80.4,70)
 Value2 <- c(0.04,0.06, 0.062)

 DF1 <- data.frame(Percent,Value1,Value2)

 Percent_A <- c(0,10,50.2,70,90.1,130.6,150,180.3)
 Value1_A <- c(100,90,88,70,60,62,62,58)
 Value2_A <- c(0.04,0.042,0.05,0.059,0.06,0.066,0.07,0.074)

 DF2 <- data.frame(Percent_A, Value1_A, Value2_A)

'''

I would like to interpolate these data frames (in reality I have many of these data frames, so it would be ideal if I can use one approach to deal with all data frames). I have some basic understanding of interpolation in R but am running into a couple of problems.

  1. I would like these data frames to be interpolated into new data frames with y values given for every single-percentage value. This is causing me issues for two reasons (1: the data frames have two different max(Percent) values; 2: max(Percent) values are frequently not whole numbers). Based on my limited interpolation in R knowledge, the approxfun function seems useful, but I am unsure how to interpolate into every 1 percentage units, where the max known percentage value is not a whole number.

  2. It would be great if I could interpolate Value1 and Value2 (in relation to Percent) for a given DF at the same time.

I would love your knowledge and insight on this matter! Thank you for the time and consideration on this topic.

Here is a rough version of one approach. The red points show the initial data.

Percent <- c(0,30.4,99.6)
Value1 <- c(100,80.4,70)
Value2 <- c(0.04,0.06, 0.062)

DF1 <- data.frame(Percent,Value1,Value2)

Percent_A <- c(0,10,50.2,70,90.1,130.6,150,180.3)
Value1_A <- c(100,90,88,70,60,62,62,58)
Value2_A <- c(0.04,0.042,0.05,0.059,0.06,0.066,0.07,0.074)

DF2 <- data.frame(Percent_A, Value1_A, Value2_A)

InterpFunc <- function(DF){
  FUN1 <- approxfun(DF[, 1],DF[, 2])
  FUN2 <- approxfun(DF[, 1],DF[, 3])
  X1 <- ceiling(min(DF[, 1]))
  X2 <- floor(max(DF[, 1]))
  NewY1 <- FUN1(X1:X2)
  NewY2 <- FUN2(X1:X2)
  data.frame(Perc = X1:X2, NewY1, NewY2)
}
InterpDF1 <- InterpFunc(DF1)
plot(InterpDF1[, 1], InterpDF1[, 2])
points(DF1[, 1], DF1[, 2], col = "red", pch=17)

plot(InterpDF1$Perc, InterpDF1$NewY2)
points(DF1[, 1], DF1[, 3], col = "red", pch=17)

InterpDF2 <- InterpFunc(DF2)
plot(InterpDF2[, 1], InterpDF2[, 2])
points(DF2[, 1], DF2[, 2], col = "red", pch=17)

plot(InterpDF2$Perc, InterpDF2$NewY2)
points(DF2[, 1], DF2[, 3], col = "red", pch=17)

Created on 2021-10-28 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.