rdataframeimputets

Using function na_ma in a numeric dataframe in R


I am trying to use the function na_ma from library(imputeTS); because I am dealing with missing values in a dataframe by replacing them with the average of the surrounding values.

Data example:

i1<-c(5,4,3,4,5)
i2<-c(2,NA,4,5,3)
i3<-c(NA,4,4,4,5)
i4<-c(3,5,5,NA,2)
data<-as.data.frame(cbind(i1,i2,i3,i4))
data

My code

data %>%
    rowwise %>%
        na_ma(as.numeric(x), k = 1, weighting = "simple")

The expected result:

i1 i2 i3 i4
1  5  2 2.5  3
2  4  4  4  5
3  3  4  4  5
4  4  5  4 4.5
5  5  3  5  2

The problem, I don't know how to apply na_ma(as.numeric(x), k = 1, weighting = "simple") to each row of this dataframe.

Thank you!


Solution

  • If you want to use tidyverse to do this you may use pmap_df.

    library(dplyr)
    library(purrr)
    
    data %>%
      pmap_df(~imputeTS::na_ma(c(...), k = 1, weighting = "simple"))
    
    #     i1    i2    i3    i4
    #  <dbl> <dbl> <dbl> <dbl>
    #1     5     2   2.5   3  
    #2     4     4   4     5  
    #3     3     4   4     5  
    #4     4     5   4     4.5
    #5     5     3   5     2  
    

    This can also be done in base R -

    data[] <- t(apply(data, 1, imputeTS::na_ma, k = 1, weighting = "simple"))