Problems when attempting to use "na_ma" on a list of data frames?

147 Views Asked by At

I am a fairly novice R user, but have been trying to do some simple missing value replacement. (Replacing an NA with the mean of the value before and the value after the NA)

I have been using the na_ma() function from the imputeTS library and it is doing exactly what I need to do.

na_ma(x , k=1, weighting = "simple") 

I have applied it to a column, then a data frame and it all worked fine. I now wish to apply it to a list of data frames but it does not seem to be working.

If anyone could point me in the right direction on what my best option for this issue would be I would greatly appreciate it.

1

There are 1 best solutions below

1
Steffen Moritz On

Should be pretty simple either use lapply or a loop.

Here is a reproducible example - lapply:

library("imputeTS")

a <- data.frame(x1 <- c(2,NA,NA,2,4,6,6), x2 <- c(2,NA,7,2,NA,6,6))
b <- data.frame(x1 <- c(2,NA,33,2,4,61,6), x2 <- c(22,NA,71,2,NA,36,6))

# this is your list with data.frames that contain columns with NAs
l <- list(a,b)

# Don't forget to assign the result of lapply back to your list l
l <-lapply(l, function(x) na_ma(x , k=1, weighting = "simple"))
l

Here an example with a list:

library("imputeTS")

# Create Example data
a <- data.frame(x1 <- c(2,NA,NA,2,4,6,6), x2 <- c(2,NA,7,2,NA,6,6))
b <- data.frame(x1 <- c(2,NA,33,2,4,61,6), x2 <- c(22,NA,71,2,NA,36,6))
l <- list(a,b)


for (i in length(l)) 
{
  l[[i]] <- na_ma(l[[i]] , k=1, weighting = "simple")
}
l 

The for loop version might have the advantage, that warnings or errors are better traceable. But anyway both version should work I guess.