1

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.

Steffen Moritz
  • 7,277
  • 11
  • 36
  • 55
  • You may wish to try `lapply`, with applies a function to items in a list. For example `lapply(my_list, function(x) na_ma(x , k=1, weighting = "simple"))` , where obviously you would change `my_list` to whatever your list is actually called (Though you don't need to change anything else in the call) – Allan Cameron Nov 08 '21 at 12:39
  • Thank you for your reply! I have tried the variations of apply. Including lapply and how you suggested, the code runs but doesn't seem to perform the function (NAs are still there) which seems strange. I also then tried to add a set number of data frames to the scope : lapply(mylist[1:3]... But I receive an error message saying "attempt to apply non function" – Jimbo Biggly Nov 08 '21 at 13:41

1 Answers1

0

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.

Steffen Moritz
  • 7,277
  • 11
  • 36
  • 55
  • Thank you! I was forgetting to assign the result. Thank you for taking your time to answer. I really appreciate it. – Jimbo Biggly Nov 18 '21 at 13:34