0
votes

I have two year data for each ID, where y2011 and y2016 represents the data of 2011 and 2016 respectively.

id <- c(1:5)
y2011 <- c(100,200,150,121,20)
y2016 <- c(111,195,180,121,25)

dat <- data.frame(id, y2011, y2016)

Now I want to estimate approximate data of middle years 2012, 2013, 2014, 2015 by using interpolation. How can I do this using R? I have tried approx function in R.

approx(dat$y2011, dat$y2016)

But do not get proper solution.

1
What does your code using approx look like? We may be able to fix it for you without starting from scratch.MrFlick
I have tried using this - approx(dat$y2011, dat$y2016) .Rudro88

1 Answers

3
votes

Here's one option. You need to call approx for each row essentially so i use mapply for that.

middle_years <- t(mapply(function(a, b) approx(c(2011,2016), c(a,b), 2012:2015)$y, dat$y2011, dat$y2016))
colnames(middle_years) <- paste0("y", 2012:2015)

cbind(dat, middle_years)
#   id y2011 y2016 y2012 y2013 y2014 y2015
# 1  1   100   111 102.2 104.4 106.6 108.8
# 2  2   200   195 199.0 198.0 197.0 196.0
# 3  3   150   180 156.0 162.0 168.0 174.0
# 4  4   121   121 121.0 121.0 121.0 121.0
# 5  5    20    25  21.0  22.0  23.0  24.0