Home > Blockchain >  Using function na_ma in a numeric dataframe in R
Using function na_ma in a numeric dataframe in R

Time:09-30

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!

CodePudding user response:

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"))

CodePudding user response:

Are you really sure you want to do this? Normally we impute column-wise, with the mean of the columns.

cm <- colMeans(dat, na.rm=TRUE)
dat <- Map(\(x, y) ifelse(is.na(x), y, x), data, cm) |>
  as.data.frame()
dat
#   i1  i2   i3   i4
# 1  5 2.0 4.25 3.00
# 2  4 3.5 4.00 5.00
# 3  3 4.0 4.00 5.00
# 4  4 5.0 4.00 3.75
# 5  5 3.0 5.00 2.00

Actually it's better to use more sophisticated imputation techniques such as multiple imputation. Here a reading.


Data

dat <- structure(list(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)), class = "data.frame", row.names = c(NA, 
-5L))
  • Related