T X
T X

Reputation: 613

How to fill missing data according to the date previous and next to it in R?

Two more questions about this topic: A B

Take Fig.1 as an example, we can see that data in 10/12/2016 12:07 is missing. I want to use the previous and next row of data (i.e., 10/10/2016 10:50 5.73; 10/24/2016 08:53 6.09) to linear interpolate this missing data (not the mean value of "5.73" and "6.09", but according to the "date"). The example data file is attached below:

09/26/2016 11:57    5.42
10/10/2016 10:50    5.73
10/12/2016 12:07    
10/24/2016 08:53    6.09
11/07/2016 11:25    6.43
11/21/2016 13:57    6.33
12/05/2016 14:01    7.97
12/19/2016 13:00    8.47

You can see Fig.2, we can use "Trend()" to attain this goal.

=TREND(M22:M23,L22:L23,O22)

I was wondering if there is a useful function as well in R?

Fig-1 Fig-2

Upvotes: 1

Views: 190

Answers (1)

Jay Achar
Jay Achar

Reputation: 1271

Example data:

df <- data.frame(date = mdy_hm(
                    c("10/10/2016 10:50",
                      "10/12/2016 12:07",
                      "10/24/2016 08:53")),
            figure = c(5.73, NA_real_, 6.09))

Using the zoo package:

library(zoo)    
library(magrittr)

zoo(df$figure, df$date) %>% 
      na.approx() %>% 
      as.data.frame()

Using lubridate and dplyr

library(dplyr)
library(lubridate)

df %>% 
   mutate(figure = ifelse(is.na(figure),
                      lag(figure, 1) + (lead(figure, 1) - lag(figure, 1)) *
                      as.numeric(difftime(date, lag(date, 1))) / 
                      as.numeric((difftime(lead(date, 1), date) + difftime(date, lag(date, 1)))),
                      figure)) %>% 
   mutate(figure = round(figure, 2))

Upvotes: 2

Related Questions